user4182981
user4182981

Reputation:

Why a class with only static methods is used?

I want to know the reasons for creating a class with only static methods, for example the Console or the Convert classes. The only reason I can think of is to group related functions together, so how is this different from a namespace.

Upvotes: 3

Views: 316

Answers (3)

Wolfgang S.
Wolfgang S.

Reputation: 21

You already have the point. Maybe it becomes clear when u see when we use such classes in our very big project cluster:

We use such a class e.g. as Utilities and Constants functionality in our project cluster.

That means you can use such utilities like as ConvertXFromYtoZ or WriteDebug anytime without taking care of the instance of the object.

We use also 'a lot' of different constants. Its very fine to have them in one static place: Constants.MyArea_Type_Foo.

By the way, it is also nice to have the static Regex.Match class. I nearly never use the dynamic Regex class.

Upvotes: 0

Dario Griffo
Dario Griffo

Reputation: 4284

A good answer to this is this interview to Stroustrup, talking about invariants. If a class doesn't modify any of its properties, or doesn't have a property you may want static methods.

http://slesinsky.org/brian/code/stroustrup_on_invariants.html

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 157136

There is just one console, so why do you need to instantiate a class? There is no need for it. That is just one reason. (This is just a way to implement the singleton design pattern)

Another reason could be that the methods are not related to an instance, they are just helper method, like Convert.XXX. Related to this are extension methods, that are obligated to be in a static class, also since they are not related to an instance of the class they are contained in.

Namespaces can't contain methods, so you need a class to wrap them in.

Upvotes: 6

Related Questions