Static Class: Declared with Static keyword, methods in Static Class are also static along with variables of the class.
This class cannot be instantiated, i.e we cannot have objects of this class. To access methods of this class, you can directly use classname.method. Also this class cannot be inherited.
This class cannot be instantiated, i.e we cannot have objects of this class. To access methods of this class, you can directly use classname.method. Also this class cannot be inherited.
If a class is declared as static then the variables and methods should compulsorily be declared as static.
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 or simply constructors as we know that they are associated with objects and operates on data when an object is created.
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}