Data Haunting

Easy Solutions Destination


Understand static keyword with example in c#

This article will explain about static class and members of static class like static method and static variables . To access static method and static variables doesn’t need to create instance of it’s class . Let’s try to demonstrate by example .

Create a simple class with static method and static variables

Now if we will try to access this class by creating instance of that class we can’t access static method and static variables .

 Static method can not access non static field 

one thing we have to keep in mind that static method never can access non static member like non static variable . Let’s see what happened.

So while we try to access non static variable we have error that “An object reference is required for the non-static field, method, or property”  because we have not created instance of class so variable “nonStaticVariable” has no memory . We can call static member because they are already loaded in static memory .

Features of Static members

  1. static class are sealed by default so we can’t inherit static class .
  2. static class have no behavior at all so does need to derive it.
  3. static member are already loaded in memory (static memory) so we can access it without creating instance of that class
  4. all constant  variables are static default so we does not required to define it static and directly can access without creating it’s instances.

When to use Static Members

Suppose we have numbers of helpers and utility methods which we need to use many times and these are methods which are generic in nature at that time we can use static members like static class , static methods and statics variables because they are already in static memory so it is bitter fast compare to creating instance to access those class and methods .


Leave a Reply