Static vs non static keyword in C# full Explanation
In C#, the `static` and `non-static` keywords are
used to define the behavior and characteristics of members (variables, methods,
properties, etc.) within a class. Here's a full explanation of the `static` and
`non-static` keywords in C#:
1.
Static Members:
v Static
members belong to the class itself rather than to instances (objects) of the
class.
v They
are associated with the type and can be accessed directly using the class name,
without creating an instance of the class.
v Static
members are shared among all instances of the class and have a single copy in
memory.
v Common
examples of static members are static variables, static methods, and static
properties.
v Example:
public class MyClass
{
public static int Count; // Static variable
public static void PrintCount() // Static method
{
Console.WriteLine("Count:
" + Count);
}
}
- Usage:
MyClass.Count = 10; // Accessing static variable
MyClass.PrintCount(); // Calling static method
2.
Non-Static Members:
v Non-static
members belong to instances (objects) of the class and require an instance to
access them.
v Each
instance of a class has its own copy of non-static members, and they can have Different
values.
v Non-static
members can access both static and non-static members of the class.
v Examples
of non-static members include instance variables, instance methods, and
instance properties.
v Example:
public class MyClass
{
public int Number; // Instance variable
public void PrintNumber() // Instance method
{
Console.WriteLine("Number:
" + Number);
}
}
- Usage:
MyClass obj1 = new MyClass();
obj1.Number = 5; // Accessing instance variable
obj1.PrintNumber(); // Calling instance method
3.
Usage Considerations:
v Static
members are commonly used for utility methods, constants, shared resources, or
global settings that are independent of individual instances.
v Non-static
members are used for instance-specific functionality and data that can vary
among Different instances of a class.
v Static
members can be accessed directly using the class name, while non-static members
require an instance of the class to access them.
v Static
members can be accessed within both static and non-static members, but
non-static members can only access static members indirectly using the class
name.
v Static
members are initialized once when the class is first accessed, whereas
non-static members are initialized separately for each instance of the class.
Understanding the difference between `static` and `non-static` members in C# is crucial for designing classes and organizing your code effectively. By choosing the appropriate keyword for members, you can control their behavior, memory usage, and access patterns in your C# programs.
0 Comments