Understanding Static vs Non-Static Variables in C#

Understanding Static variables
Whenever a variable has a static keyword or is declared inside the static block, the variable is considered static.

Here is an example.

 

You can make the variable static when you want that variable to have the same values through all instances that will be created.

Static vs Non-Static variables
Static variables are initialized when once the execution of the class starts, on the other side non-static variables initialize after the object is created.

Non-static variables get initialized n times depending on how many times the object is created, but static variables only initiate once during the lifecycle.

You can call the static variable of class outside of class but for non-static you need to instance to call the variable.

 

This example shows how static variables can be called and how nonstatic variables can be called.

The outcome of this code is

static value of yesstatic 200
static value of yesStatic within the class 200
non-static value of nonStatic 100

Scope of Static and Non-Static
For the static variable, the scope is Application scope which means it is created when class execution starts and it lasts as long as the application last.

Non-static variable is created when the object is created and also gets deleted when the object is deleted.

Also when you want to use a non-static variable in the static method you need to instantiate first to use a non-static variable, without instance you cannot use a non-static variable in a static method

Static and Non-Static constructor
If we make a static constructor we need to call it on top, before any other constructor and there only can be one static constructor in a class. also static constructor is only called once in the application's lifetime

Meanwhile non-static constructor is called on every object created.

Ebook Download
View all
Learn
View all
GE HealthCare will never ask for payment to process documents, refer you to a third party to process