Static Class and Static Members in C#
Static classes are classes that do not contain instance members other than those inherited from Object, and do not have a callable constructor.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.
Envirnoment class is a good example of a static class. You need not create a new instance of the class with new keyword to get access to its members. You can directly access its members as shown below
Console.WriteLine(Environment.MachineName);
Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name.
For example, MyClass.StatMember
Because static members are not associated with object instances, they do not have access to non-static members (which are accessed through "this," which represents the current object instance).
Non-static members are called instance members because they are associated with individual object instances. Think of static members as belonging to the class and instance members belonging to instances of the class (that is, objects).
class ClsTea
{
public string Brand
{
get
{
return _brand;
}
set
{
_brand = value;
}
}
}
The above is a non-static member and can be accessed by an instance of the class as shown below:
ClsTea MyTea = new ClsTea();
MyTea.Brand = "Tata";
Console.WriteLine("My favourite tea brand is " + MyTea.Brand);
Qualifying the member with the name of the class like ClsTea.Brand = "Tata"; will throw an ‘An object reference is required for the nonstatic field, method, or property 'member'’ exception
A static member can be accessed as shown below
class ClsTea
{
private static string _brand;
public static string Brand
{
get
{
return _brand;
}
set
{
_brand = value;
}
}
}
ClsTea.Brand = "Tata";
Console.WriteLine("My favourite tea brand is " + ClsTea.Brand);
Here the Member is directly qualified using the Class Name (no instantiation is required)
Using the class objects to access a static member will throw an “Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead” error
ClsTea MyTea = new ClsTea();
MyTea.Brand = "Tata";
.NET What are Static Classes?, C# What are Static Classes?, .NET What are Static Functions/methods?, C# What are Static Functions/methods?, How to access a static member in C#, How to access an instance (non-static0 member in C#
No comments:
Post a Comment