Hello Friends, In this tutorial we are going to discuss Static Vs Non Static Keyword in C#. Both Static and Non-Static have their own purpose. We are going to discuss them here.
After completing this tutorial we would be able to understand:
- What is Static Class, Static Methods?
- Static vs Non-Static in C#.
Static vs Non Static Keyword in C#:
The term static defines relating to itself. A Static Class is similar to itself with the difference is that we cannot create an instance of a static class. In another word, we cannot use new keyword with the static class to create an instance of the class. Since we cannot create an instance of a static Class, we can access the members of the static class using the class name directly.
If we declare a method or variable as static inside the class we can access the member of that class using the class name no need to create an object of that class.
A Static Variable can be used for those values which cannot be stored by instance. For example, if I need to keep count of how many instances of a class exist, we can use a static variable in such type of scenario.
There are following characteristics related to Static Class.
- A Static Class can contain only static members.
- We cannot create an instance of the Static class.
- When you define a class as static you do not have access to the Non-Static field of that class. You can use only static members of that class.
- A Static class cannot implement the interface.
- You cannot add an abstract keyword to static class they are implicitly abstract.
- There is no default constructor for the static class. Also, we cannot create a Constructor for Static Class.
Let’s create an example using Static and Non Static method in C#.
Open Visual Studio and Create a C# application.
Non-Static Method Example:
You can see in the above example we have created a Non-Static method called NonStaticCall. Since it is a Non-Static method we can call this method after creating an instance of the class that is what I did in the Main method. I have created an Instance of the Program Class and called the NonStaticCall method.
Static Method Example:
As in the above program, I have created a Static method called StaticCall. We don’t need to create an instance of the class for calling this static method. We can just call this method using Class Name as we did above.
Hope you loved this post about Static Vs Non Static Keyword in C#. I would appreciate your Feedback, Comments and Suggest.