C# supports static classes and static members. A static class can’t be instantiated. A C# class can have static or non-static members. A static member has only one copy of the member, regardless of the number of instances. Static members and their values belong to the type itself rather than the object. If multiple instances of a class are created, the last updated value of a static member will be available to all instances.
The static modifier in C# declares a static member of a class. The static modifier can be used with classes, properties, methods, fields, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes.
Static Class
A static class cannot be instantiated. All members of a static class are static and are accessed via the class name directly, without creating an instance of the class.
The following code is an example of a static class, CSharpCorner. We know that all members of the class are static.
public static class CSharpCorner
{
// Static fields
public static string Name = "C# Corner";
public static string Founder = "Mahesh Chand";
public static DateTime YearFounded = new DateTime(2000, 01, 01);
public static string Location = "Downingtown, PA";
public static string Description =
"Online community of software and data developers";
public static int GetAgeOfWebsite()
{
return 1;
}
}
Static classes have the following characteristics:
- Static classes cannot contain Instance Constructors.
- Static classes contain only static members.
- Static classes cannot be instantiated.
- Static classes are sealed. That means you cannot inherit other classes from instance classes.
Static Members
A static or non-static class static constructors, properties, methods, fields, operators, and events. Static properties and static methods are the most-used static members.
Static Constructor
- Static constructors can't be parameterized.
- A static constructor has no access modifier because it doesn't have message passing and is used during domain processing.
- Static Constructor is used to initializing static data members of the class.
Static Field
A field with the static keyword represents a static field. Static fields can be declared as follows by using the static keyword.
public static class HistoryTeacher
{
// static field
public static string Subject = "History";
}
The following code calls a static field.
Console.WriteLine(HistoryTeacher.Subject);
When we declare static data members inside a class, it can be initialized with a value, as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded for the first time.
Static Property
Static properties are used to get or set the value of static data members of a class. The following code example declares four static properties.
public static class HistoryTeacher
{
// private fields
private static string name;
private static string school;
private static int rank;
private static int years;
// static properties
public static int Years { get => years; set => years = value; }
public static int Rank { get => rank; set => rank = value; }
public static string School { get => school; set => school = value; }
public static string Name { get => name; set => name = value; }
}
The following code example sets static property values.
HistoryTeacher.Name = "Mahesh Chand";
HistoryTeacher.Rank = 2;
HistoryTeacher.School = "Garnet Valley High School";
HistoryTeacher.Years = 5;
In the same way, you can access a static property by using the class name.
Console.WriteLine(HistoryTeacher.Name);
Static Method
Static methods are shared methods. They can be called with the class name and static method name only. You cannot instantiate a static method.
Static methods only use static data members to perform calculations or processing.
The following code example declares a static method that takes two int values as method arguments.
public static class HistoryTeacher
{
// static method
public static int CalculateScore(int rank, int years)
{
return rank * years;
}
}
The following code example calls a static method.
Console.WriteLine(HistoryTeacher.CalculateScore(3, 5));
Why use static classes and static members?
Static classes are used as containers for static members. Static methods and static properties are the most-used members of a static class. All static members are called directly using the class name. Static methods do a specific job and are called directly using a type name, rather than the instance of a type.
Here is a list of a few use cases of static classes.
- A Math class with all static methods. Static classes are useful and provide an easy way to access their members that do not need to work differently for different objects.
- Above listed CSharpCorner class. We know the value of CSharpCorner class members, such as its founder, launch date, location, and description, will never change regardless of its objects.
- App Configuration class that has all static settings about an app, and the values of settings don’t change based on the objects or users.
- A DatabaseConfig class may have members such as database name, server name, port number, and even a connection string. We know that these values will not change for objects.
- Static classes and static members are useful because they do not require instances created for each new object. That means, they consume fewer resources, and no duplication of the same class or member is needed in memory.
Static members make code cleaner.
In theory, a static should give better performance compared to an instance. However, it is unnoticeable.
Complete Code Example of C# Static
Here is a complete program that shows how to use static classes and static members.
using System;
namespace StaticInCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(HistoryTeacher.Subject);
HistoryTeacher.Name = "Mahesh Chand";
HistoryTeacher.Rank = 2;
HistoryTeacher.School = "Garnet Valley High School";
HistoryTeacher.Years = 5;
Console.WriteLine(HistoryTeacher.Name);
Console.WriteLine(HistoryTeacher.CalculateScore(3, 5));
Console.ReadKey();
}
}
public static class HistoryTeacher
{
// static field
public static string Subject = "History";
// private fields
private static string name;
private static string school;
private static int rank;
private static int years;
// static properties
public static int Years { get => years; set => years = value; }
public static int Rank { get => rank; set => rank = value; }
public static string School { get => school; set => school = value; }
public static string Name { get => name; set => name = value; }
// static method
public static int CalculateScore(int rank, int years)
{
return rank * years;
}
}
}
Summary
In this article, I discussed what static classes are in C# and how to use a static class in your C# application.
Niloy NiloyPosted Oct 25, 2023, 3:27 AM
How to access non static members of a static class
Mohd NuriPosted Jan 26, 2021, 4:24 AM
Is there any problem with this implementation public static class DirectDB { private const string Err_Fac_Rec_Not_Found = "DirectDB: Facility record not found"; private const string Err_Rec_Not_Updated = "DirectDB: Record not updated"; private const string Err_Cust_Rec_Not_Found = "DirectDB: Customer record not found"; private const string Err_Package_Attribute_Not_Found = "DirectDB: Package not found"; public static bool UpdatePaymentAmount(long lFacID, decimal dPayAmt, decimal dFinPayAmt, out string sErr) { Microsoft.Practices.EnterpriseLibrary.Data.Database oDB = null; int iRes = 0; System.Data.Common.DbCommand oDBCmd = null; sErr = string.Empty; string strSQL = "UPDATE tblFOSDATLNApplFacility SET Instalment = @Instalment, FinalInstalment = @FinalInstalment WHERE FacID = @FacID"; try { if (lFacID > 0) { oDB = Helper.DBConnect.GetDatabase(); oDBCmd = oDB.GetSqlStringCommand(strSQL); oDB.AddInParameter(oDBCmd, "FacID", DbType.Int64, lFacID); oDB.AddInParameter(oDBCmd, "Instalment", DbType.Decimal, dPayAmt); oDB.AddInParameter(oDBCmd, "FinalInstalment", DbType.Decimal, dFinPayAmt); iRes = oDB.ExecuteNonQuery(oDBCmd); } else { sErr = Err_Fac_Rec_Not_Found; } if (iRes <= 0) sErr = Err_Rec_Not_Updated; return iRes > 0; // I expect a record to be updated } catch (Exception ex) { sErr = ex.Message; return false; } finally { if (oDBCmd != null) { oDBCmd.Dispose(); oDBCmd = null; } } }
Jayesh AgrawalPosted May 13, 2019, 12:30 PM
Very informative...want to add one point: we should avoid static variables for configuration or db connections (user specific) when it is shared with multi user. i.e public static userName {get; set;} so, multiple user are accessing it, every time it will override userName variable. Users will not get correct userName.
Scott HannenPosted May 3, 2019, 8:46 AM
I'd be a little concerned about using static classes for configuration or database connections. The only use for those classes is for other classes to depend on them. Other classes that depend on static classes can be very difficult to test. Static classes are good for static methods, as you mentioned, like math.
Gajanan ChavhanPosted May 2, 2019, 9:30 AM
Thank you. very useful information. I think there is on typo in statement "A Match class with all static methods", here expected "Math" in place of "Match".
Geoffrey PaynePosted May 2, 2019, 2:22 AM
It would be interesting to look deeper at the decision making process for deciding whether or not to use a static class, taking into consideration that you do not want to create a static class only to change it to a non-static class later.