TheVillageIdiot
TheVillageIdiot

Reputation: 40497

What are the gains of converting normal method to static?

As it is clear from question, if I convert a normal method to static what gains will I made?

Upvotes: 4

Views: 178

Answers (3)

Ian Kemp
Ian Kemp

Reputation: 29839

Apart from the semantic reasons mentioned above, static methods are generally faster (due to not having to create an object to call the method). They are subject to compile-time optimisations and as far as I recall, the CLR also performs some special optimisations on them.

Upvotes: 1

Prashant Cholachagudda
Prashant Cholachagudda

Reputation: 13092

Static function normally used for utility stuffs like ConverThisTypeToThatType(), and you can call them without having object of its class.

Ex: MessageBox.Show("Something");

here MessageBox is a Class and Show is static method in it, so we dont need to create object of MessageBox to call Show.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

You will gain clarity, because static makes it clear that the method doesn’t depend on an object state. You will also facilitate reusability because static methods may be used in more contexts (i.e. when you don’t have an instance of the class).

In general, it’s not really a question of gain, it’s a question of semantics: does your method depend on the object state? If so, make it non-static. In all other cases, make it static.

Upvotes: 13

Related Questions