Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a class not have a static or constant property and an instance property of the same name?

Tags:

c#

I've never really questioned this before until now. I've got an input model with a number of fields, I wanted to present the string names of the properties through the input model so that my Grid can use them:

public class SomeGridRow
{
    public string Code { get;set; }
    public string Description { get;set; }

    public const string Code = "Code";
}

Obviously, this gives the error:

The type 'SomeGridRow' already contains a definition for 'Code'

Why can the CLR not cope with two properties of the same name which are, in my eyes, separate?

string code = gridRow.Code;          // Actual member from instantiated class
string codeField = SomeGridRow.Code; // Static/Const

I'm now just using a child class called Fields within my inputs now, so I can use SomeGridRow.Fields.Code. It's a bit messy, but it works.

like image 951
djdd87 Avatar asked Oct 06 '10 09:10

djdd87


3 Answers

Because you can also access static (or, non-instance in this case) properties in the same way (inside the same class), and it would be a bit confusing, for example:

public class SomeGridRow
{
  public string Code { get;set; }
  public const string Code = "Code";
  public void MyMethod() {
    var thing = Code; //what would this reference?
  }
}

Because both this:

public class SomeGridRow
{
  public string Code { get;set; }
  public void MyMethod() {
    var thing = Code; //what would this reference?
  }
}

And this:

public class SomeGridRow
{
  public const string Code = "Code";
  public void MyMethod() {
    var thing = Code; //what would this reference?
  }
}

are valid ways to access properties, static or not. It doesn't answer the "why can't I?" question, but more of the why it's not allowed...it would be far too ambiguous IMO.

like image 123
Nick Craver Avatar answered Nov 10 '22 10:11

Nick Craver


It probably could, but the designers of C# wanted to avoid ambiguities that can come from such use (abuse?) of language features.

Such code would end up being confusing and ambiguous to users (did I want the instance or the static method call?, Which one is right?).

like image 45
Oded Avatar answered Nov 10 '22 08:11

Oded


In addition to the points already made about ambiguity, i would say that the naming needs to be relooked in such a case.

If two variables / fields having the exact same name in the same context i.e class but different values to me sounds more like a naming issue.

If they are exactly same, you dont need 2 fields.

If they are slightly different, you should have more accurate names.

like image 42
Jagmag Avatar answered Nov 10 '22 10:11

Jagmag