Is there a programmatic way to identify .Net reserved words? [closed]
Asked Answered
P

2

17

I am looking for reading .Net, C# reserved key words programmatically in VS 2015.

I got the answer to read C# reserved words in the [link][1].

CSharpCodeProvider cs = new CSharpCodeProvider();
var test = cs.IsValidIdentifier("new"); // returns false
var test2 = cs.IsValidIdentifier("new1"); // returns true

But for var, dynamic, List, Dictionary etc the above code is returning wrong result.

Is there any way to identify .net keywords in run time instead of listing key words in a list?

string[] _keywords = new[] { "List", "Dictionary" };
Parkman answered 31/5, 2016 at 5:35 Comment(17)
just because I am very curious. Why do you need this? :DAnglofrench
It very much seems like an XY Problem. This solves some other problem you aren't describing.Rumney
I think you mean C# instead of .NET.Admit
bytes.com/topic/c-sharp/answers/…Scarper
What exactly do you mean? Neither var nor dynamic nor List are keywords. Please explain your question.Forenoon
digging into the roslyn kode i found this gem source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/… could this be a way to go ?Anglofrench
@Forenoon - im guessing he means reserved wordsAnglofrench
List/Dictionary are not keywords in C#.Carboxylase
The API you are trying to use simply tells you if a word is reserved keyword in C# or not. var, dynamic etc are NOT reserved keywords. The result being returned from the API is correct.Nance
Creating a keyword list is the correct way, you can find the keywords here.Carboxylase
All reserved keywords can be found here : blogs.msdn.microsoft.com/ericlippert/2009/05/11/…Nance
By "reserved" do you mean character sequences that satisfy the rules for identifiers but cannot be used as identifiers without special handling?Admit
@StianStandahl There are no other "reserved" words. His examples are simply wrong. The reserved words are the ones in the list and not a single one more.Forenoon
I am still interested in the use case. What is the use case here?Anglofrench
@Forenoon - thanks for the clarification.Anglofrench
I'm not sure why people are hounding you so much on a use case. This is a simple and obvious enough question that it can be answered without a motivation. In case you need one, though, how about configuring a syntax highlighting control's "keywords" list. For example, the Scintilla control uses one. What if I don't want to maintain my own hard-coded list that I will have to update each time a new language spec comes out, introducing a new keyword? Wouldn't it be cooler if I could just recompile?Reversion
@CodyGray So would var be a keyword in your example? Because it's not a reserved word.Forenoon
F
32

This is a perfectly fine C# program:

using System;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            int var = 7;
            string dynamic = "test";
            double List = 1.23;

            Console.WriteLine(var);
            Console.WriteLine(dynamic);
            Console.WriteLine(List);
        }
    }
}

So your premise is wrong. You can find the keywords by looking them up in the short list. Just because something has a meaning does not mean it's in any way "reserved".

Do not let the online syntax highlighting confuse you. Copy and paste it into Visual Studio if you want to see proper highlighting.

Forenoon answered 31/5, 2016 at 6:3 Comment(3)
Even crazier, you can add a type called var which is then used instead of type inference.Nerine
@Nerine It's not crazy - it's exactly as designed. Each successive version of C# needs to remain backwards compatible with previous versions, so whatever code was valid in C# 2.0 must still be valid in C# 3.0. This is the reason why async exists, for example - it was the best way to ensure that await isn't misinterpreted in old code compiled in the newer compiler. Once you add the async, it's your responsibility to fix any conflicts.Piggott
@Luaan: It's a perfectly sensible language design choice, but it is perfectly crazy user behaviour. The language designers have to come up with designs that are robust in the face of crazy user behaviour.Maimonides
V
4

As explained by nvoigt, your method of programmatically determining if a string is a keyword is effectively correct. To be complete, (after checking Reflector) it should be:

bool IsKeyword(string s)
{
    var cscp = new CSharpCodeProvider();
    return s != null
           && CodeGenerator.IsValidLanguageIndependentIdentifier(s)
           && s.Length <= 512
           && !cscp.IsValidIdentifier(s);
}

(The VB.NET version needs 1023 and a check for "_".)

Veliavelick answered 31/5, 2016 at 17:7 Comment(4)
IsKeyword(string s) is workinng, but only for C# keywords. And I am looking more like words like List, Dictioonary etc also should recognize by my program.Parkman
@Parkman In that case, you want to also enumerate all public types in the namespaces you're considering, or to look up every time, enumerate all the namespaces you're considering and check for a non-null result from Type.GetType(ns+Type.Delimiter+s)..Veliavelick
Thanks Mark, for types I am validating in all types available in a namespace. C# key words I am using CSharpCodeProvider.IsValidIdentifier, But C# Contextual Keywords are not validating trough above Two.Parkman
My comment above is not completely correct. Type.GetType will only return the type if it's in "the currently executing assembly or in Mscorlib.dll", unless you provide an assembly qualified name.Veliavelick

© 2022 - 2024 — McMap. All rights reserved.