2

I have a Utils unit in my app which, as of right now, only has a few enums defined, such as:

public enum MostFavoredStates
{
    California,
    NorthCarolina,
    Vermont,
    NewMexico
}

public enum LeastFavoredStates
{
    NorthDakota,
    Illinois,
    Nebraska
}

public enum StatesInWhichIHaveResided
{
        California,
        NewYork,
        Montana,
    Alaska,
        Oklahoma,
        Wisconsin,
        Idaho,
        Missouri
}

When I run ReSharper on my project, it says I need no "using" statements at all in this class; so, I remove them all, and voila! it really does need nothing at all.

"enum" must be declared somewhere - how can it live without a reference to that assembly or namespace? If there's something "baked in" to every class, what is it?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

3 Answers3

12

"enum" must be declared somewhere - how can it live without a reference to that assembly or namespace? If there's something "baked in" to every class, what is it?

"enum" is a C# language keyword. It is not a framework type that needs to be resolved, as it's part of the language itself.

Note that there are many other language keywords that are this way. For example, you can use int without a using clause for using System;, as it's "baked into" the language as an alias to System.Int32 - but you can't use Int32, since that is System.Int32.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

You never need any using statements at the start of your program; their entire existence is for convenience.

You can always use the fully qualified name for every type inline and it will be resolved.

System.Console.WriteLine(System.String.Empty);

The above snippet compiles just fine without any using blocks. The only advantage of adding using System; is that it lets your shorten the above code to:

Console.WriteLine(String.Empty);

Now, given the number of times types of certain namespaces are generally used in a given code file, this tends to be a significant improvement, such that fully qualified names are rarely used.

The type aliases (int, string, double, datetime, etc.) map to the fully qualified name of what they represent, not just un-qualified name, so there is no dependence on using System.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

Its important to note that the C# "baked in" types such as int and string are just aliases for for the .NET types System.Int32 and System.String.

If you use int or string you hence dont need the using System.

If you are trying to decide which to use (the .NET type or the C# alias) the following SO question might help:

C#, int or Int32? Should I care?

Community
  • 1
  • 1
bytedev
  • 8,252
  • 4
  • 48
  • 56