-4

I'm wondering I can't reach static class field from instance variable

    class aa
    {
        public static string b = "bb";
    }

    Console.WriteLine(aa.b); //fine
    aa f = new aa();
    f.b //error

Why? Do I make something wrong?

vico
  • 17,051
  • 45
  • 159
  • 315
  • 1
    I think other languages like Java allow this, but this is not supported in C#. – Kobi Oct 08 '18 at 09:39
  • 3
    Yep. static methods and properties can only be accessed from the type not an instance of the class. As such static methods do not have acces to non-static properties or methods – phuzi Oct 08 '18 at 09:39

1 Answers1

0

Outside you can get a static field by ClassName.StaticVariable, but inside the class it is similar to other instance variables. This is because static variables are owned by class, not a specific instance.

smolchanovsky
  • 1,775
  • 2
  • 15
  • 29
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members – smolchanovsky Oct 08 '18 at 09:53