Search code examples
c#classconstantsrenamepublic

Renamed c# class and now I can't access the public const variables in that class


I renamed one of my c# classes and now I can't access the 'public const byte' variables in that class. I renamed it in the solution explorer and when it asked if I would like to perform a rename in the project of all references to the code element 'className' I selected 'Yes'.

The error message I'm getting is: "Member 'Namespace1.Class1.CONSTANT_NUM' cannot be accessed with an instance reference; qualify it with a type name instead".

Everything else in the class works (i.e. the methods and non-const fields) but I don't know why I'm not able to access the public const fields any longer?? Any ideas?


Solution

  • A constant is associated with a particular type, rather than a particular instance (considered static).

    Your error message is telling you that you're trying to access a const from a particular class instance, rather than a type.

    So if your class was:

    public class Class1()
    {
        public const int MY_INT = 5;
    }
    

    You may well be trying to do this somewhere in your code:

    Class1 thisInstance = new Class1();
    Console.WriteLine(thisInstance.MY_INT); // Will cause an error.
    

    What you probably want to be doing is this:

    Console.WriteLine(Class1.MY_INT);
    

    Edit: It might be the case that before the error, your instance name was the same as your type name, and the compiler couldn't infer what you meant.