Static Classes in C#
This topic contains and tries to cover following subjects:
- Explanation of Static Classes in C#
- An example of Static Class in C# with basic console application example
- Syntax of Static Class in C#
#Explanation of Static Classes
In a C# Class, the methods or fields can be static to be used without instantiating-creating object of the Class. A known example of Static Class usage is Console Class which is used in console applications to provide output in console output with static method "WriteLine()".
Apart from making a field or method static, C# supports static Classes. Idea behind of making a Class Static is to get help from Visual Studio to prevent unwanted object creations. In following image it is shown: a non-static Class with static field has been declared. Due to the static field, it is possible to access its field without instantiating it.
Class itself is still available to be instantiate. When it is planned to design a Class with all members static, it is a better practice to make it static.
What are the benefits or purpose of Static Classes can be question. Mainly two reason addresses the answer:
1. Static Classes guarantee that a instance is never created.
2. Visual Studio checks Static Class members in compile time. When Class is static, non-static member declaration is compiler time error. It helps consistent Class development.
#Example of Static Class in C#
Static Class Example contains following steps:
- Created a console Application
- Added a Class which had been demonstrated at earlier screenshot. Static keyword is addded preceding Class keyword
- Added one Static Class field
Following console application is created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NS_hardwareManagerApp
{
static class CL_notebooks
{
public static string field_notebookName;
}
class CL_x
{
static void Main(string [] args)
{
}
}
}
Preceding code snippet, creating an object-instance from that Class ends up with compiler error. Also VS indicates non-static member definition declarations within Class.
MSDN link below explains static Classes with more detail.