Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding Static class in c# [duplicate]

Tags:

c#

static

Possible Duplicate:
When to Use Static Classes in C#

why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.

thanks

like image 408
Thomas Avatar asked Aug 29 '26 18:08

Thomas


2 Answers

A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.

like image 164
Rick Sladkey Avatar answered Aug 31 '26 06:08

Rick Sladkey


Generally I would advise you not to write static classes.

There are cases where you want them though

Extension methods have to live on static classes. This is the best reason to have a static class.

If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.

Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.

Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.

like image 37
Neil Avatar answered Aug 31 '26 06:08

Neil