Static Vs Non Static Method in C#
Today I was browsing through the asp.net forums. I came across a post by AidyF, where He have explained the difference between Static and Non static Method in C# in a very deliberate manner. I would like to share the same with you guys..
First lets start with MSDN definition:
MSDN Definition: A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, we cannot use the new keyword to create a variable of the class type. Because there is no instance variable, we access the members of a static class by using the class name itself.
C# fields must be declared inside a class. However, if we declare a method or a field as static, we can call the method or access the field using the name of the class. No instance is required. We can also use the static keyword when defining a field. With this feature, we can create a single field that is shared among all objects created from a single class. Non-static fields are local to each instance of an object.
When you define a static method or field, it does not have access to any instance fields defined for the class; it can use only fields that are marked as static. Furthermore, it can directly invoke only other methods in the class that are marked as static; nonstatic (instance) methods or fields first require creation of an object on which to call them.
Now let us look into a basic example:
Mixing static and non-static resources and each accessing the other:
The following Code Snippet covers some likely real-world scenarios. It's really up to you to decide when your code should use static or non-static methods and properties, there is no one-size-fits-all solution to every scenario. But these are some more real-world examples that will maybe give you some context (after all, we add and subtract using "+" and "-", we don't write maths classes).