I don’t know, maybe I’m missing something or maybe I’m just stupid (you can pick, just let me know):
class User
{
public static readonly int ID; // class property
public int ID; // instance property
}
Compiling this little cutie returns the error:
“ The type ‘ConsoleApplication1.User’ already contains a definition for ‘ID’ “
What’s going on here ? This properties are completely different, one is *instance* property and the other is *class* property. What is the conflict here? Am I missing some Microsoft spec on this one? Am I missing some OOP lesson? Is it C# restriction? Is it CLI restriction ?
I’m confused…
Off the top of my head, I’d say that this rule is in place so that when you’re inside, let’s say, a method, that you don’t have to qualify your fields as either ‘this.ID’ or ‘User.ID’, but simply be able to write ‘ID’ and be done with it.
Again, this is sheer speculation.
I’d suggest you just find a more meaningful name for the static-readonly field. :)
@Oren,
This is a CLR restriction, there are languages (VB) that allows you to access class members via instance ones.
As Omer has mentioned, this can cause issues with code inside the class
Why would you want to do this?
As methods have signatures to be identified uniquely, variables must be unique classwide. Access modifiers etc. are not part of the signature. Otherwise, we would also be able to write
class User
{
public static void GetID(){}
public void GetID(){} // Compile time error: Type User already defines a member called GetID with the same parameter types
private void GetID(){} // same here
}
Section 3.6 of the spec talks about signatures. Although not mentioning the applicability to variables, I believe you can get the picture.
I see,
Well, it makes some sense.
OK, I guess I’ll have to use Enum for this one.