Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what is the purpose of marking a class static?

In C#, what is the purpose of marking a class static?

If I have a class that has only static methods, I can mark the class static or not. Why would I want to mark the class static? Would I ever NOT want to mark a class static, if all the methods are static, and if I plan to never add a non-static method?

I looked around and saw some similar questions, but none that were just like this.

like image 723
Cheeso Avatar asked Feb 11 '10 22:02

Cheeso


People also ask

What does || mean in C?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

What is ?: operator in C?

In other words, we can also say that an operator is a symbol that tells the compiler to perform specific mathematical, conditional, or logical functions. It is a symbol that operates on a value or a variable. For example, + and - are the operators to perform addition and subtraction in any C program.

What is the use of in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.


2 Answers

Marking a class as static is a declarative statement that you only intend for this type to have static and const members. This is enforced by the compiler and prevents you from accidentally adding an instance method to the type.

Other advantages

  • Extension methods can only be defined in static classes
  • Prevents users from creating an instance of the class
  • Prevents use of the type as a generic argument (thanks Eric!)
like image 124
JaredPar Avatar answered Oct 04 '22 16:10

JaredPar


Marking a class as static gets you two important things.

  • Compiler verification that you only put static members in a class.

  • An obvious statement to readers of your code that this class is only a container for static members.

The feature was invented in response to a bug in NDP v1.0, where a un-callable non-static member was included in the System.Environment class.

like image 26
Jay Bazuzi Avatar answered Oct 04 '22 16:10

Jay Bazuzi