ragnar
ragnar

Reputation: 73

Access static member when type and variable has same name

How do I tell the compiler that the "Thing" in "Thing.VariableProperty" is the type not the instance? Like this it says that my instance of Thing does not contain a definition of VariableProperty.

Or is it wrong of me to use the type name as variable name also?

  public interface IThing
  {
    int Variable { get; }
  }

  public class Thing : IThing
  {
    public const string VariableProperty = nameof(Variable);

    public int Variable => 1;
  }


  public class MyClass
  {
    public IThing Thing = new Thing();

    public string GiveMeAString()
    {
      return "Something about " + Thing.VariableProperty;
    }
  }

Upvotes: 0

Views: 323

Answers (1)

Streamline
Streamline

Reputation: 982

You can use the fully qualified name of the Test class, if it is in a namespace, or you can use the global keyword to refer to the class:

...
public string GiveMeAString()
{
    return "Something about " + global::Thing.VariableProperty;
    // Or
    // return "Something about " + My.Namespace.Thing.VariableProperty;
}
...

A third way would be to use the using static directive:

using static Thing;

...
public string GiveMeAString()
{
    return "Something about " + VariableProperty;
}
...

But in this case i would recommend to either use another name for the Thing class like e.g SpecializedThing or to rename the MyClass.Thing field to e.g. aThing or myThing.

Upvotes: 2

Related Questions