Recent Posts

Posts RSS

Overview About Static Class & Members in C#.Net


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. Static classes can be used when there is no data or behavior in the class that depends on object identity.
Static Class:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors.
See the following example for static class:

static class CompanyInfo
                        public static string GetCompanyName() { return "CompanyName"; }
                        public static string GetCompanyAddress() { return "CompanyAddress"; }

Static Member:
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

public class Employee
                        public static int NumberOfEmp = 200;
                        public static long SalaryOfEmp
                                                return 15000;
                        public static void EmpProfile() { }
                        //other non-static fields and properties...
Employee. EmpProfile();
int i = Employee. NumberOfEmp;

Hope It Helps!

kick it on