0

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;
    }
  }
11
  • This code already works? sharplab.io/… This is the "Color Color" problem, and C# was specifically designed to permit it: blogs.msdn.microsoft.com/ericlippert/2009/07/06/color-color Commented Apr 23, 2019 at 13:04
  • @LasseVågsætherKarlsen that sounds like an answer, you should write one. Commented Apr 23, 2019 at 13:04
  • See softwareengineering.stackexchange.com/questions/212638/… Commented Apr 23, 2019 at 13:05
  • Please post your actual code. I say this because you have used @ for string interpolation, which won't work, {Thing.VariableProperty} is just text, meaning that not only would you not get a compiler error from this, it wouldn't even print what you wanted it to print. Clearly, this is not the right code. Can you please post your actual code so that we're not missing something? Commented Apr 23, 2019 at 13:08
  • you can do 'return @"Something about {this.Thing.VariableProperty}";' Commented Apr 23, 2019 at 13:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.