Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static classes cant implement interfaces? [duplicate]

Possible Duplicate:
Why Doesn’t C# Allow Static Methods to Implement an Interface?

In my application I want to use a Repository that will do the raw data access (TestRepository, SqlRepository, FlatFileRepository etc). Because such a repository would be used throughout the runtime of my application it seemed like a sensible thing to me to make it a static class so I could go

SqlRepository.GetTheThingById(5); 

without it having to be regenerated all the time. Because I want my repositories to be interchangeable, I want them to implement a common interface: IRepository. But when I try to do so, I get:

Static classes cannot implement interfaces

Why can't they? How do you suggest I change my design then? Is there a pattern I could use?

UPDATE
Five years later: this question is visited 20k+ times, I learned about the disadvantages of the repository pattern, learned about IoC and realise my question was poorly formulated.

I wasn't really asking what the C# specification of an interface is, rather why it was deliberately restricting me in this specific way.

The practical answer is that the syntax for calling a method on an instance or on a type are different. But the question is closed.

like image 754
Boris Callens Avatar asked Aug 12 '09 14:08

Boris Callens


People also ask

Why static classes Cannot implement interfaces?

Static classes cannot be inherited whereas an interface must be inherited in order to use it. Making an interface static, would render it pretty much useless. You'd need to inherit it in a class to implement it's members but static would prevent you from doing exactly that.

Why static methods are not allowed in interface C#?

Polymorphism works through instances - whereas static members explicitly don't use instances. that's the reason interfaces don't have static methods.

Can static class inherit other class?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Can static class inherit abstract class?

It's not allowed because inheritance is about creating related classes of objects, and you're not creating any objects at all with static classes.


1 Answers

Interfaces can't have static methods. A class that implements an interface needs to implement them all as instance methods. Static classes can't have instance methods. QED.

like image 67
Joe White Avatar answered Oct 12 '22 17:10

Joe White