Why do I need an explicit interface declaration here? (C#) [duplicate] - c#

The use case is some what like this:
public class SomeClass : ICloneable
{
// Some Code
// Implementing interface method
public object Clone()
{
// Some Clonning Code
}
}
Now my question is Why is it not possible to use "SomeClass(As it is derived from object)" as a return type of Clone() method if we consider the Funda's of Covariance and Contravariance?
Can somebody explain me the reason behind this implementation of Microsoft ????

Let me rephrase the question:
Languages such as C++ allow an overriding method to have a more specific return type than the overridden method. For example, if we have types
abstract class Enclosure {}
class Aquarium : Enclosure {}
abstract class Animal
{
public virtual Enclosure GetEnclosure();
}
then this is not legal in C# but the equivalent code would be legal in C++:
class Fish : Animal
{
public override Aquarium GetEnclosure() { ...
What is this feature of C++ called?
The feature is called "return type covariance". (As another answer points out, it would also be possible to support "formal parameter type contravariance", though C++ does not.)
Why is it not supported in C#?
As I've pointed out many times, we don't have to provide a reason why a feature is not supported; the default state of all features is "not supported". It's only when huge amounts of time and effort are put into making an implementation that a feature becomes supported. Rather, features that are implemented must have reasons for them, and darn good reasons at that considering how much it costs to make them.
That said, there are two big "points against" this feature that are the primary things preventing it from getting done.
The CLR does not support it. In order to make this work we'd basically have to implement the exactly matching method and then make a helper method that calls it. It's doable but it gets to be messy.
Anders thinks it is not a very good language feature. Anders is the Chief Architect and if he thinks it is a bad feature, odds are good its not going to get done. (Now, mind you, we thought that named and optional parameters was not worth the cost either, but that did eventually get done. Sometimes it becomes clear that you do have to grit your teeth and implement a feature that you don't really like the aesthetics of in order to satisfy a real-world demand.)
In short, there are certainly times when it would be useful, and this is a frequently requested feature. However, it's unlikely that we're going to do it. The benefit of the feature does not pay for its costs; it considerably complicates the semantic analysis of methods, and we have no really easy way to implement it.

A non-broken implementation of interface-implementation variance would have to be covariant in the return type and contravariant in the argument types.
For example:
public interface IFoo
{
object Flurp(Array array);
}
public class GoodFoo : IFoo
{
public int Flurp(Array array) { ... }
}
public class NiceFoo : IFoo
{
public object Flurp(IEnumerable enumerable) { ... }
}
Both are legal under the "new" rules, right? But what about this:
public class QuestionableFoo : IFoo
{
public double Flurp(Array array) { ... }
public object Flurp(IEnumerable enumerable) { ... }
}
Kind of hard to tell which implicit implementation is better here. The first one is an exact match for the argument type, but not the return type. The second is an exact match for the return type, but not the argument type. I'm leaning toward the first, because whoever uses the IFoo interface can only ever give it an Array, but it's still not entirely clear.
And this isn't the worst, by far. What if we do this instead:
public class EvilFoo : IFoo
{
public object Flurp(ICollection collection) { ... }
public object Flurp(ICloneable cloneable) { ... }
}
Which one wins the prize? It's a perfectly valid overload, but ICollection and ICloneable have nothing to do with each other and Array implements both of them. I can't see an obvious solution here.
It only gets worse if we start adding overloads to the interface itself:
public interface ISuck
{
Stream Munge(ArrayList list);
Stream Munge(Hashtable ht);
string Munge(NameValueCollection nvc);
object Munge(IEnumerable enumerable);
}
public class HateHateHate : ISuck
{
public FileStream Munge(ICollection collection);
public NetworkStream Munge(IEnumerable enumerable);
public MemoryStream Munge(Hashtable ht);
public Stream Munge(ICloneable cloneable);
public object Munge(object o);
public Stream Munge(IDictionary dic);
}
Good luck trying to unravel this mystery without going insane.
Of course, all of this is moot if you assert that interface implementations should only support return-type variance and not argument-type variance. But almost everyone would consider such a half-implementation to be completely broken and start spamming bug reports, so I don't think that the C# team is going to do it.
I don't know if this is the official reason why it's not supported in C# today, but it should serve as a good example of the kind of "write-only" code that it could lead to, and part of the C# team's design philosophy is to try to prevent developers from writing awful code.

You have to implement an interface's methods exactly as they are in the interface. ICloneable's Clone method returns an object, so your SomeClass must also return an object. You can, however, return a SomeClass instance in SomeClass's Clone method without any problem, but the method definition must match the interface:
public class SomeClass: IClonable
{
// Some Code
//Implementing interface method
Public object Clone()
{
SomeClass ret = new SomeClass();
// copy date from this instance to ret
return ret;
}
}

In terms of explaining the reasons behind C# decisions, Eric Lippert from Microsoft has written much explaining Contra/CoVariance in C#... here's the tag list from his blog:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
[Edit]
Specific to your question, this might be the right post.. http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx

It looks like the kind of thing they could have used generics for, but it seems there is a good reason why they did not.
It is talked about here:
http://bytes.com/topic/c-sharp/answers/469671-generic-icloneable
Basically, a generic interface that would allow:
public class MyClass : IClonable<MyClass>
would also allow:
public class MyClass : IClonable<MyOtherClass>
which doesn’t really provide any benefit, and might confuse things.

According to the C# specification, you must use a method with an identical signature when overriding or implementing an interface method. Keep in mind that Microsoft does not own C#. Their C# compiler is simply their implementation of it. So why would the spec do things this way? I can only guess, but I suspect it was for ease of implementation.

Related

What to do when a struct ends up becoming a constraint (due to interfaces - and the compiler goes grumpy)?

EDIT:
I have come to the conclusion that it's impossible to meet all my desired requirements!
Original Question...
I appear to have run into an unfortunate dilemma. It boils down to the fact that structs are not valid generic constraints - which is perfectly sane, but a problem arises non the less...
Why would you ever want to constrain generics to a struct??
Well I don't really want to do that - it is a consequence of interface design.
I will explain my predicament by going through the process that led me there:
Say I have an interface with some (potentially) performance critical generic method, i.e:
interface ISomeInterface
{
Result RelativeComputation(ISomeInterface other);
}
However the ISomeInterface itself is not a sufficiently strong restraint: I want the details that make this computation possible to be an implementation detail - I specifically do not want to expose the required data in the interface itself because it is only needed for that one method, and to make matters worse the required data is generic (of a type not used anywhere else in that or any related interface) so exposing it would litter additional generics into every other interface or class that makes use of ISomeInterface.
So to solve the above the next logical evolution of the code is:
interface ISomeInterface<T> where T : ISomeInterface<T>
{
Result RelativeComputation(T other);
}
Now no implementation details need to be exposed, the constraint is strong, and in most cases this would be the happy ending.
However, situations can arise where T is fulfilled by another interface, i.e:
interface IOtherInterface : ISomeInterface<IOtherInterface>
{
//... *other stuff*
}
Now there are issues again! :(
Firstly, as mentioned in the beginning, this method call could end up in performance critical code, so in those cases it might be desirable to make the other parameter a struct. However with the code above this would inevitably be ruined by boxing.
Secondly the constraint on T in RelativeComputation(T other) that appeared to be strong is actually too weak - unless we choose to expose implementation details again! (Either directly in ISomeInterface as discussed before, or in IOtherInterface.)
The second issue I don't really have a good solution for, other than making IOtherInterface generic and applying the Curiously Repeating Template Pattern on it too, and then add the computation method again. The result being:
interface IOtherInterface<T> : ISomeInterface<IOtherInterface<T>>
where T : IOtherInterface<T>
{
new Result RelativeComputation(T other);
//... *other stuff*
}
...eventually the inheritance hierarchy would reach a concrete type and the implementation details will remain hidden.
This is admittedly not very elegant, but it is also not the real issue so I digress.
The real issue at hand is the "First" issue mentioned above.
At first glance it would appear easy to solve; Make the method itself generic, like so:
interface ISomeInterface<T> where T : ISomeInterface<T>
{
Result RelativeComputation<T2>(T2 other) where T2 : T;
}
Now the parameter can be a struct and there will be no boxing anymore!
(This is true even if T above is an interface, e.g. IOtherInterface.)
Great right!
So lets just make a suitable struct, i.e. implementing ISomeInterface (or a more derived interface, as IOtherInterface) and the problem is, eeh... oh.
If you haven't already figured it out, here is what that code would look like:
struct MyPerformantStruct : ISomeInterface<MyPerformantStruct>
{
Result RelativeComputation<T2>(T2 other) where T2 : MyPerformantStruct; // nope! :(
}
The interface requires that exact signature, but that does not compile!
I'm hoping there is some way to solve this?
(Allow structs with no boxing and hide as much implementation as possible!)
To clarify I don't expect there is a way to use a struct as a generic constraint, but rather I am hoping there is another workaround, like a clever design improvement (and / or hack).
EDIT:
Current answers and comments have given me insight into some additional information that is of relevance:
The interface and the implementing type can reside in different assemblies. (The interface is in a library.)
I'm not saying it has to be a struct, I'm saying it should be possible to use either a class or a struct (without boxing).
The "implementation details" I'm referring to is some value type (possibly more than one). The method in question is a bool IsLessThan(...) type of method, something I can't seem to evaluate without boxing, unboxing and runtime-checks (no thanks!) - or without knowing implementation details about the underlying type and exposing those in the interface, thus locking the implementation and defeating the whole point of the abstraction - or restricting it on the interface level, which has other issues mentioned above - or also restricting it on the method level, which is what I wanted to do above, but as it turns out that explicitly prevents T from being a struct.
(I prefer to stay on .net 3.5 but this is not critical.)
My problem description is long and it isn't instantly obvious why generics is required on both the interface and the method, so I will provide a code example and illustrate why it doesn't compile (or would require runtime casting):
This code illustrates the need to constrain to the actual type:
interface IExample
{
bool IsLessThan<T>(T other) where T : IExample;
}
class ExampleClass : IExample
{
short someValue;
public bool IsLessThan<T>(T other) where T : IExample
{
return this.someValue < other.???; // <-- what now?
}
}
First of all, you should ask a question about the actual problem you're solving. It's very hard to understand what you're trying to do, and why you're trying to do it, if you use only examples. Perhaps you're approaching the problem wrong, or is there a better solution to your actual problem. There are a myriad of design patterns that solve many problems.
It looks like you're doing micro-optimizations. Have you measured the code in question? Have you found the bottleneck to be really there?
You'd like code that looks like this:
struct MyPerformantStruct : ISomeInterface<MyPerformantStruct>
{
Result RelativeComputation<T2>(T2 other) where T2 : MyPerformantStruct;
}
But... why? If MyPerformantStruct is a struct, then, by definition, there is no class or struct whatsoever that can inherit from it. The only type that could ever satisfy T2 is... MyPerformantStruct. So why not use that directly?
interface ISomeInterface<T>
where T : struct
{
Result RelativeComputation(T other);
}
struct MyPerformantStruct : ISomeInterface<MyPerformantStruct>
{
Result RelativeComputation(MyPerformantStruct other);
}
Is there a reason T is a generic parameter on the type instead of on the member?
interface ISomeInterface
{
Result RelativeComputation<T>(T other)
where T : struct;
}
struct MyPerformantStruct : ISomeInterface
{
Result RelativeComputation<MyPerformantStruct>(MyPerformantStruct other);
}
Would your code not work with things other than structs? Seems unlikely to me, so then you could drop the struct constraint. You'd still get the benefits of unboxed structs when T is a struct.
interface ISomeInterface
{
Result RelativeComputation<T>(T other);
}
struct MyPerformantStruct : ISomeInterface
{
Result RelativeComputation<MyPerformantStruct>(MyPerformantStruct other);
}
And are you sure you can deal with this struct without boxing it, ever? If not, you might as well just abstract over the type and ask for the struct's interface, or object if you really want to. I'm guessing that the only reason you're working with structs is performance. This is the wrong approach. Structs should represent immutable values, such as a date/time pair or a percentage. Structs aren't boxless collections of mutable fields that you use for performance reasons. And you'll run into issues later on if you try to use them as such.
There are two different problems in your question: struct constraints in generic type definitions with regards to boxing, and how to hide implementation details inside an assembly.
As you pointed out, you cannot set a generic type parameter to be of an explicit struct type. You can, however, enforce a generic type parameter T to both be a struct and implement a specific interface:
interface ISomeInterface<T> where T : struct, ISomeInterface<T>
{
Result RelativeComputation(T other);
}
Now about boxing: generics are meant to prevent boxing from happening (see Benefits of Generics). Consider the following program:
public interface ISomeInterface
{
int GetValue();
}
public struct SomeStruct : ISomeInterface
{
public int GetValue() { return 42; }
}
public interface ISomeOtherInterface1<T> where T : ISomeInterface
{
int ComputeStuff(T other);
}
public interface ISomeOtherInterface2<T> where T : struct, ISomeInterface
{
int ComputeStuff(T other);
}
class ClassImplementingInterface1<T> : ISomeOtherInterface1<T> where T : ISomeInterface
{
public int ComputeStuff(T other) { return other.GetValue(); }
}
class ClassImplementingInterface2<T> : ISomeOtherInterface2<T> where T : struct, ISomeInterface
{
public int ComputeStuff(T other) { return other.GetValue(); }
}
class Program
{
static void Main(string[] args)
{
var value = new SomeStruct();
var obj1 = new ClassImplementingInterface1<SomeStruct>();
var obj2 = new ClassImplementingInterface2<SomeStruct>();
var obj3 = new ClassImplementingInterface1<ISomeInterface>();
var result1 = obj1.ComputeStuff(value);
var result2 = obj2.ComputeStuff(value);
var result3 = obj3.ComputeStuff(value);
}
}
In this exemple I have an interface that is implemented by a struct, and two different generic interfaces: the second one enforces its generic type parameter to be a struct where the first doesn't. In the Main method you see 3 different ways of using those classes. If you look at the assembly code produced by the last 3 lines of code in the Disassembly window in Visual Studio, you will see that the code for the first two calls are identical: no boxing occurs. The assembly code of those two ComputeStuff methods are also identical, because both the code and the effective type parameters are identical. Only the last one causes boxing to happen because it uses the ISomeInterface type as the effective type parameter, and interface types are reference types in the CLR world so any value type passed will indeed be boxed.
About hiding implementation details, it seems unclear to me what you are trying to hide to external code exactly, but maybe what you are missing is that it is possible for public types to implement internal interfaces, if they implement them explicitly:
internal struct PrivateData { ... }
internal interface IMyInterface
{
Result SomePrivateComputation(PrivateData data);
}
public class MyPublicClass : IMyInterface
{
Result IMyInterface.SomePrivateComputation(PrivateData data)
{
...
}
}
Then your code in its assembly (and friend assemblies specified by any InternalsVisibleToAttribute) will be able to do the following:
MyPublicClass myObj;
...
((IMyInterface)myObj).SomePrivateComputation(myData); // No boxing here, no virtual call either: the compiler knows which method to invoke on MyPublicClass.
I've come to the conclusion that what I like to do can not be done.
Something has to give, and in this case it will simply be IOtherInterface.
Simply put, if one wishes to use a struct and not suffer any boxing T in ISomeInterface has to be the struct itself (with the method no longer having its own generics).
Any workaround I can think of would absolutely cost more than a simple boxing instruction.
So I'm closing this as not doable.
Thanks for your replies people.

Why the concept of "Covariance" and "Contravariance" are applicable while implementing the methods of an interface?

The use case is some what like this:
public class SomeClass : ICloneable
{
// Some Code
// Implementing interface method
public object Clone()
{
// Some Clonning Code
}
}
Now my question is Why is it not possible to use "SomeClass(As it is derived from object)" as a return type of Clone() method if we consider the Funda's of Covariance and Contravariance?
Can somebody explain me the reason behind this implementation of Microsoft ????
Let me rephrase the question:
Languages such as C++ allow an overriding method to have a more specific return type than the overridden method. For example, if we have types
abstract class Enclosure {}
class Aquarium : Enclosure {}
abstract class Animal
{
public virtual Enclosure GetEnclosure();
}
then this is not legal in C# but the equivalent code would be legal in C++:
class Fish : Animal
{
public override Aquarium GetEnclosure() { ...
What is this feature of C++ called?
The feature is called "return type covariance". (As another answer points out, it would also be possible to support "formal parameter type contravariance", though C++ does not.)
Why is it not supported in C#?
As I've pointed out many times, we don't have to provide a reason why a feature is not supported; the default state of all features is "not supported". It's only when huge amounts of time and effort are put into making an implementation that a feature becomes supported. Rather, features that are implemented must have reasons for them, and darn good reasons at that considering how much it costs to make them.
That said, there are two big "points against" this feature that are the primary things preventing it from getting done.
The CLR does not support it. In order to make this work we'd basically have to implement the exactly matching method and then make a helper method that calls it. It's doable but it gets to be messy.
Anders thinks it is not a very good language feature. Anders is the Chief Architect and if he thinks it is a bad feature, odds are good its not going to get done. (Now, mind you, we thought that named and optional parameters was not worth the cost either, but that did eventually get done. Sometimes it becomes clear that you do have to grit your teeth and implement a feature that you don't really like the aesthetics of in order to satisfy a real-world demand.)
In short, there are certainly times when it would be useful, and this is a frequently requested feature. However, it's unlikely that we're going to do it. The benefit of the feature does not pay for its costs; it considerably complicates the semantic analysis of methods, and we have no really easy way to implement it.
A non-broken implementation of interface-implementation variance would have to be covariant in the return type and contravariant in the argument types.
For example:
public interface IFoo
{
object Flurp(Array array);
}
public class GoodFoo : IFoo
{
public int Flurp(Array array) { ... }
}
public class NiceFoo : IFoo
{
public object Flurp(IEnumerable enumerable) { ... }
}
Both are legal under the "new" rules, right? But what about this:
public class QuestionableFoo : IFoo
{
public double Flurp(Array array) { ... }
public object Flurp(IEnumerable enumerable) { ... }
}
Kind of hard to tell which implicit implementation is better here. The first one is an exact match for the argument type, but not the return type. The second is an exact match for the return type, but not the argument type. I'm leaning toward the first, because whoever uses the IFoo interface can only ever give it an Array, but it's still not entirely clear.
And this isn't the worst, by far. What if we do this instead:
public class EvilFoo : IFoo
{
public object Flurp(ICollection collection) { ... }
public object Flurp(ICloneable cloneable) { ... }
}
Which one wins the prize? It's a perfectly valid overload, but ICollection and ICloneable have nothing to do with each other and Array implements both of them. I can't see an obvious solution here.
It only gets worse if we start adding overloads to the interface itself:
public interface ISuck
{
Stream Munge(ArrayList list);
Stream Munge(Hashtable ht);
string Munge(NameValueCollection nvc);
object Munge(IEnumerable enumerable);
}
public class HateHateHate : ISuck
{
public FileStream Munge(ICollection collection);
public NetworkStream Munge(IEnumerable enumerable);
public MemoryStream Munge(Hashtable ht);
public Stream Munge(ICloneable cloneable);
public object Munge(object o);
public Stream Munge(IDictionary dic);
}
Good luck trying to unravel this mystery without going insane.
Of course, all of this is moot if you assert that interface implementations should only support return-type variance and not argument-type variance. But almost everyone would consider such a half-implementation to be completely broken and start spamming bug reports, so I don't think that the C# team is going to do it.
I don't know if this is the official reason why it's not supported in C# today, but it should serve as a good example of the kind of "write-only" code that it could lead to, and part of the C# team's design philosophy is to try to prevent developers from writing awful code.
You have to implement an interface's methods exactly as they are in the interface. ICloneable's Clone method returns an object, so your SomeClass must also return an object. You can, however, return a SomeClass instance in SomeClass's Clone method without any problem, but the method definition must match the interface:
public class SomeClass: IClonable
{
// Some Code
//Implementing interface method
Public object Clone()
{
SomeClass ret = new SomeClass();
// copy date from this instance to ret
return ret;
}
}
In terms of explaining the reasons behind C# decisions, Eric Lippert from Microsoft has written much explaining Contra/CoVariance in C#... here's the tag list from his blog:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx
[Edit]
Specific to your question, this might be the right post.. http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx
It looks like the kind of thing they could have used generics for, but it seems there is a good reason why they did not.
It is talked about here:
http://bytes.com/topic/c-sharp/answers/469671-generic-icloneable
Basically, a generic interface that would allow:
public class MyClass : IClonable<MyClass>
would also allow:
public class MyClass : IClonable<MyOtherClass>
which doesn’t really provide any benefit, and might confuse things.
According to the C# specification, you must use a method with an identical signature when overriding or implementing an interface method. Keep in mind that Microsoft does not own C#. Their C# compiler is simply their implementation of it. So why would the spec do things this way? I can only guess, but I suspect it was for ease of implementation.

C#: Optional method

I have an object that implements an interface. I want to call on the object's method if it is implemented. What's the best way in doing this?
Update
A few of you mentioned that my question was vague. Sorry about that. When i said "if it is implemented" i meant "if it is callable". Thanks for your answers and effort guys (or girls!). I'm amazed how much developer support there is on this website.
If this really the way you need it to work, an interface is the wrong choice. Instead, you could have an abstract class from which your class derives with a virtual method. Virtual allows it to be overridden, but does not require it. Since a virtual method has an implementation, it cannot be part of an interface.
Not quite sure what you mean by "if it is implemented." If the method is in the interface and your object implements the interface it must implement the method.
If you want to test if an object implements the interface so you can call the method, you can do it like so:
interface IFoo { void Bar(); }
object o = GetObjectThatMayImplementIFoo();
IFoo foo = o as IFoo;
if (foo != null) {
foo.Bar();
}
I think that's what you were asking?
Create two interfaces, and inherit both interfaces where all methods are required. Inherit only one of the interfaces where the optional methods aren't required.
You can also create a base interface, from which all your interface will inherit, for OOP uses.
I think what you're really looking for is a partial method. These are new in .NET 3.5. You simply declare the method as "partial":
partial void OnLoaded();
The method can be called normally:
OnLoaded();
The neat thing is that if the method is not implemented anywhere, the compiler is smart enough not to generate the call.
This was implemented primarily for LINQ to SQL and for Entity Framework; this allows generated code (using partial classes) to define and call methods without knowing whether they are implemented.
Mixing partial methods with interfaces would be interesting (I haven't tried it), but my first try would be declaring a partial method in the interface.
Shouldn't the object's class implement every method of the interface?
If the object's class inherits from an abstract class, it is possible that it might not override("implement") some methods. Perhaps you are mixing the two up in your mind.
As with the other answers, I'm not sure what you mean. The closest that a class implementing an interface can get to not implementing one of the interface methods is throwing a NotImplementedException. The way to handle this is to specifically catch that exception when calling the method. However, the whole point of an interface is to define a contract between classes, so maybe some clarification would help.
My first response is don't do this. It creates conditional logic around the possibility of a method being there, it goes against the statically typeness of C# and breaks a couple of the SOLID principles. My experience tells me this is the wrong path to walk down.
With that said it can be done via Reflection or using the 'is/as' solution wojo demonstrates.
This type of behavior might be better implemented in a dynamic language. It sounds similar to Duck typing. I'm not a dynamic language guy, but if you have unit tests, it may be alright.
You cannot really know if the method is actually implemented (or if the class just has a "dummy" implementation). Therefore, you may use a pattern such as one of the following to find out if a specific method is supported:
-> Have multiple interfaces and see if the class actually implements it; this is probably the cleanest way to deal with it, but it may leave you with a large number of different interfaces, which may not be desirable:
IIntfA = inst as IIntfA;
if (inst != null) {
// inst seems to be implemented
}
-> Use methods in the TryXxx style, which return true if they were successfull (like TryParse() etc.).
-> Use NotImplementedException - but note that catching those is very expensive and should only be used for calls which are performed rarely, or where a missing implementation is not expected. The Stream class works like this, for instance if it cannot be written to (but additionally there is a property telling what the class supports, e.g. IsWritable in the Stream class).
Hey guys, don't forget the "is" keyword :P
You can check if an object implements an interface like this too:
if (inst is IInterface)
{
// you can safely cast it
}
I prefer it that way but of course you could also use the "as" keyword
IInterface a = inst as IInterface;
if (a != null)
{
// use a, already casted
}
Depending on how you're referencing an object, certain members will be visible. An interface might be implicitly defined or explicitly defined, or might be implemented by a derived class and you're using a base class reference. In other words, it's not always immediately evident all the available members on an object.
So if you want to test for implementation of a certain interface (ISomething) by your object (yourObj), one choice is testing the data type, using reflection. Based on the result of this test, you can explicitly cast an implementing object into the interface Type and use its members...
if (yourObj is ISomething)
((ISomething)yourObj).DoSomething();
This is the same thing done another way (more "wordy" using method calls):
if (typeof(ISomething).IsAssignableFrom(yourObj.GetType()))
((ISomething)yourObj).DoSomething();
This sample assumes the ISomething interface is defined as:
public interface ISomething {
void DoSomething();
// other members ...
}
In summary, this code says: if the interface ISomething Is-Assignable-From your object of choice, then your object implements that interface and therefore has those public members.
I don't know if you might be looking for something like this. This uses an attribute that you can flag a method with whether or not it is implemented. Next I added an extension method to the interface to allow for checking if ithe method is implemented. Finally, the code will allow you to ask an object if the method is implemented. I don't like this but it might be what you are looking for.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
public static class Program
{
static void Main(string[] args)
{
EmployeeA empA = new EmployeeA();
if (empA.IsImplemented("TestMethod"))
empA.TestMethod();
EmployeeB empB = new EmployeeB();
if (empB.IsImplemented("TestMethod"))
empB.TestMethod();
Console.ReadLine();
}
public static bool IsImplemented(this IEmp emp, string methodName)
{
ImplementedAttribute impAtt;
MethodInfo info = emp.GetType().GetMethod(methodName);
impAtt = Attribute.GetCustomAttribute(info, typeof(ImplementedAttribute), false)
as ImplementedAttribute;
return (impAtt == null) ? true : impAtt.Implemented;
}
}
public class EmployeeA : IEmp
{
#region IEmp Members
[Implemented(false)]
public void TestMethod()
{
Console.WriteLine("Inside of EmployeeA");
}
#endregion
}
public class EmployeeB : IEmp
{
#region IEmp Members
[Implemented(true)]
public void TestMethod()
{
Console.WriteLine("Inside of EmployeeB");
}
#endregion
}
public class ImplementedAttribute : Attribute
{
public bool Implemented { get; set; }
public ImplementedAttribute():this(true)
{
}
public ImplementedAttribute(bool implemented)
{
Implemented = implemented;
}
}
public interface IEmp
{
void TestMethod();
}
}
EDIT: After original author reworded question, you definitely just want to implement the interface guranteeing the method does exist. I will leave above code for curiosity sake.

Explicit implementation of interface's GetEnumerator causes stack overflow

I'm doing my best to code against interfaces whenever possible, but I'm having some issues when it comes to collections. For example, here are a couple interfaces I'd like to use.
public interface IThing {}
public interface IThings : IEnumerable<IThing> {}
Here are the implementations. In order to implement IEnumerable<IThing> I need to explicitly implement IEnumerable<IThing>.GetEnumerator() in Things.
public class Thing : IThing {}
public class Things : List<Thing>, IThings
{
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
// This calls itself over and over
return this.Cast<IThing>().GetEnumerator();
}
}
The problem is that the GetEnumerator implementation causes a stack overflow. It calls itself over and over again. I can't figure out why it'd decide to call that implementation of GetEnumerator instead of the implementation provided by the result of this.Cast<IThing>(). Any ideas what I'm doing wrong? I'm willing to bet it's something extremely silly...
Here's some simple test code for the above classes:
static void Enumerate(IThings things)
{
foreach (IThing thing in things)
{
Console.WriteLine("You'll never get here.");
}
}
static void Main()
{
Things things = new Things();
things.Add(new Thing());
Enumerate(things);
}
Use this instead:
public class Things : List<Thing>, IThings
{
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
foreach (Thing t in this)
{
yield return t;
}
}
}
Or you could work with containment instead.
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
// This calls itself over and over
return this.Cast<IThing>().GetEnumerator();
}
It's a recursive call with no break condition, you're going to get a stack overflow, because it's going to very quickly fill up the stack.
You're casting to an interface, which does not do what you think it does. In the end you are just calling this.GetEnumerator(); which is the function you're already in, thus recursing. Perhaps you mean base.GetEnumerator();
Generally, you would probably want to decouple the implementation of the Things collection from the implementation of the Thing object. The Things class is capable of working with any implementation of IThing, not just the Thing class.
Specifically:
public class Things : List<IThing>, IThings
{
}
In this case, you don't have to override the default implementation of GetEnumerator(), the base implementation is already typed correctly for you. This will avoid the overflow that you're currently experiencing and satisfies the test case you provided.
This is a nice example of the need for the language and runtime to understand covariance and contravariance.
In C# 4, you can just use
IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()
{
return base.GetEnumerator();
}
Seems pretty obvious that this.Cast<IThing>() returns an IEnumerable. Or, at least it does without the implementation of Cast.
I don't know if a question qualifies as an answer but bear with me Im a consultant ;P Why do you wanna implement the GetEnumerator()?
You're deriving from List if you change that to List you get the GetEnumerator for free.
Be aware too that deriving from List is generally a bad idea. you should consider deriving from IEnumerable<()IThings> (as you're already doing which is atm superflurous since List also implements that interface) or if you need the List interface and not only the IEnumerable implement IList and keep a private List object. That way you get full control about the implementation and only expose a design contract (through the implemented interfaces)

Why Doesn't C# Allow Static Methods to Implement an Interface?

Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here is an example of what I have in mind:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Assuming you are asking why you can't do this:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.
For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):
...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.
Note that Lippert does leave room for a so-called type method:
That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).
but is yet to be convinced of its usefulness.
Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.
Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.
For example:
Repository GetRepository<T>()
{
//need to call T.IsQueryable, but can't!!!
//need to call T.RowCount
//need to call T.DoSomeStaticMath(int param)
}
...
var r = GetRepository<Customer>()
Unfortunately, I can come up only with "ugly" alternatives:
Use reflection
Ugly and beats the idea of interfaces and polymorphism.
Create completely separate factory class
This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.
Instantiate and then call the desired interface method
This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.
Example:
public class Customer
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
void SomeOtherMethod()
{
//do work...
}
}
in order to use instantination for solving the static interface problem we need to do the following thing:
public class Customer: IDoSomeStaticMath
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
//dummy instance
public Customer() { IsDummy = true; }
int DoSomeStaticMath(int a) { }
void SomeOtherMethod()
{
if(!IsDummy)
{
//do work...
}
}
}
This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!
I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:
string DoSomething<T>() where T:ISomeFunction
{
if (T.someFunction())
...
}
Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:
Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.
None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface,
How would you call it??
public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
public static void MyMethod() { //Do Something; }
}
// inside of some other class ...
// How would you call the method on the interface ???
MyClass.MyMethod(); // this calls the method normally
// not through the interface...
// This next fails you can't cast a classname to a different type...
// Only instances can be Cast to a different type...
MyInterface myItf = MyClass as MyInterface;
Actually, it does.
As of Mid-2022, the current version of C# has full support for so-called static abstract members:
interface INumber<T>
{
static abstract T Zero { get; }
}
struct Fraction : INumber<Fraction>
{
public static Fraction Zero { get; } = new Fraction();
public long Numerator;
public ulong Denominator;
....
}
Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see Use preview features & preview language in Visual Studio).
See more:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
https://blog.ndepend.com/c-11-static-abstract-members/
https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Because interfaces are in inheritance structure, and static methods don't inherit well.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.
To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":
When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:
interface IDataRow {
string GetDataSTructre(); // How to read data from the DB
void Read(IDBDataRow); // How to populate this datarow from DB data
}
public class DataTable<T> : List<T> where T : IDataRow {
public string GetDataStructure()
// Desired: Static or Type method:
// return (T.GetDataStructure());
// Required: Instantiate a new class:
return (new T().GetDataStructure());
}
}
The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.
FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.
Interfaces are abstract sets of defined available functionality.
Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.
If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.
Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.
I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.
Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls "static method".
The fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.
Optimist about c# though...
OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a
static public bool IsHandled(XElement xml)
function which is called in turn on each class.
The function should be static as otherwise we waste time creating inappropriate objects.
As #Ian Boyde points out it could be done in a factory class, but this just adds complexity.
It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.
However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.
So it is a minor potential feature which on balance is probably best left out.
The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.
An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.
Here is a very clear example of where being able to use interfaces with static classes would be quite useful:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
Static Methods within an Interface are allowed as of c# 9 (see https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9).
I think the short answer is "because it is of zero usefulness".
To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}
As per Object oriented concept Interface implemented by classes and
have contract to access these implemented function(or methods) using
object.
So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.
Conceptually there is no reason why an interface could not define a contract that includes static methods.
For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).
A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.
So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).
An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.

Categories

Resources