Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can not have Shared(static) function/methods in an interface/abstract class?

Tags:

.net

In .net we are not allowed to have shared function/methods in abstract classes and interfaces. Why they are not allowed ?

Is this same in other languages. like Java ?

What can be the potential problem if the Shared methods are allowed ?

like image 523
Biswanath Avatar asked Dec 01 '08 09:12

Biswanath


1 Answers

You can certainly have static (shared) methods in abstract classes. You can't have them in interfaces, however.

It sounds like you really want virtual static/shared methods - and those aren't available. Static methods aren't called polymorphically, and with the way that most of .NET works, that wouldn't make a lot of sense. It would make sense to be able to specify static methods in interfaces when using them as type parameter constraints - an idea I've blogged about before now.

Delphi has the concept of a meta-class, where (as I understand it) instance methods in a class's meta-class are like static methods in the class itself - and one meta-class can derive from another, overriding the methods etc. I'm not a Delphi programmer, but chapter 2 of Delphi in a Nutshell might be useful to you if you want more information.

Java allows constants to be specified in interfaces, but that's the only kind of static member supported there.

Interestingly, the CLI itself does allow static methods in an interface, but that's methods with bodies - not just the signature which is provided by instance members of an interface.

like image 74
Jon Skeet Avatar answered Oct 21 '22 17:10

Jon Skeet