Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Static class call means "content at address ? "

Tags:

c#

Just i have a bit of confusion in understanding static reference.

incase of instance reference we can understand when i declare

Car myCar = new Car();

Car yourCar = new Car();

---------------                       --------------
stack                                 Managed Heap
----------------                      --------------
                                        -----
myCar         ------- > points to       Car
                                        -----
YourCar       ------- > points to       Car
                                        -----

-----------------                     ---------------

What if the case of Static class ? can i mean it when i declare

staticClass.MyMethod( )

-----------------
Managed Heap
----------------
staticClass
(Memory Address ) 
----------------- 

Update: Since class is blueprint and objects are physical entities;Incase of static class when i declare staticClass.MyMethod or staticClass.MyField = value ,am i directly interacting with heap ?(As no instance is allowed for static class).

like image 958
user160677 Avatar asked Sep 07 '09 12:09

user160677


1 Answers

No, static in C# basically means "related to the type rather than an instance of the type".

Any static method is resolved statically - i.e. at compile time - so calling

StaticClass.MyMethod()

just resolves to a call to the static method, with no instance involved at all. There's nothing to point to, other than the type itself (which is sort of done implicitly).

Note that you're not allowed to declare a variable of a type which is a static class.

EDIT: Basically, the difference here is between a static method and an instance method. It so happens that static classes can't have instance methods, and you can't create instance methods, but there's no difference between:

StaticClass.StaticMethod();

and

NormalClass.StaticMethod();

and even

SomeValueType.StaticMethod();

EDIT: To respond to your edit:

  • When you set a static field, that does indeed affect the heap, but I believe it's a slightly different area of heap memory than the normal gen0/gen1/gen2 heap. (I think there's on heap per AppDomain for static variables, basically.)
  • When you call a static method, that's basically going to end up in the JITted code as a call to a bit of code at a particular address. In other words, it'll be in some executable piece of memory, but not in the area of memory used for instance data.

EDIT: I'm not sure what you mean by "application level scope" - but a static variable is associated with the type, which is associated with the AppDomain. The variable will be preserved as long as the AppDomain is loaded. It could be unloaded for various reasons.

like image 158
Jon Skeet Avatar answered Sep 29 '22 20:09

Jon Skeet