Search code examples
c#staticinstance

c# how assign static class to instance variable?


Static members can't be called with instance, like instance.myStaticProperty.

Is there any way, that I can have an instance variable that will be an alias of static self class? like:

class myClass
{
    public string a ="hello";
    public static string b ="world";

    public myClass myVariable = global::myClass;   // <--- phseudo code
}

and i could call:

myClass instance= new myClass();
instance.myVariable.b; //

Solution

  • No, there is not. The closest you get is using a using.

    Your static class definition:

    class ClassA
    {
        public static string A = "A";
    }
    

    And to use it:

    using StaticClassA = ConsoleApp1.ClassA;
    
    class Program
    {
        static void Main(string[] args)
        {
            string a = StaticClassA.A;
        }
    }
    

    Not too much to gain though, but it might ease your naming a little.

    Another (somewhat cooler) option is a static using:

    using static ConsoleApp1.StaticClassA;
    
    class Program
    {
        static void Main(string[] args)
        {
            string a = A;
        }
    }