Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )

I was asked the above question in an interview. Could you please explain the differences? ( performance - memory - usage - when to use which ? )

Thank you,

Erkan

like image 546
Erkan Y. Avatar asked Feb 15 '10 16:02

Erkan Y.


People also ask

What is difference between static method and non static method in C#?

Difference between static and non-static classStatic class is defined using static keyword. Non-Static class is not defined by using static keyword. In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword.

What is the difference between static class and non static class in C#?

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.

What is the use of static method in non static class C#?

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.

What is the difference between static class and class with static methods?

A static class can only contain static members. A static method ensures that, even if you were to create multiple classB objects, they would only utilize a single, shared SomeMethod function. Technically, there's no difference, except that ClassA's SomeMethod must be static.


2 Answers

Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.

A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:

  1. Provide a factory method for creating an instance of that type;
  2. Provide helper functionality that does not require an instance of the type;

Also, as mentioned already, extension methods can only be declared on a static class.

like image 104
Seth Petry-Johnson Avatar answered Sep 19 '22 21:09

Seth Petry-Johnson


I assume you were asked for the differences?

A static method on a static class can be used to define an extension method. A static method on a non-static class cannot.

like image 26
JaredPar Avatar answered Sep 20 '22 21:09

JaredPar