C# - How are we supposed to implement default(T) in Interfaces?
Put default(T)
in an interface. Explicitly implement the interface. The result does not compile
public interface IWhatever<T>
{
List<T> Foo(T BarObject = default(T));
}
public class ConcreteWhatever: IWhatever<ConcreteWhatever>
{
List<ConcreteWhatever> Fo开发者_运维百科o(ConcreteWhatever BarObject = default(T)) {}
}
I fully expect default(ConcreteWhatever)
. What I get is default(T)
which results in a compilation error.
I just go in and replace default(T)
with null
and things are fine. But this is hideous. Why is this happening?
You don't have a T
in this case, because ConcreteWherever
isn't a generic type.
If you want default(ConcreteWhatever)
then that's the code you should write.
Are you just complaining about the code auto-generated by Visual Studio? If so, that's a reasonable complaint, but it would be worth being explicit about it... (Note that you're not using explicit interface implementation here - otherwise it would be declared as IWhatever<ConcreteWhatever>.Foo
. You don't really have properly implicit implementation either, as otherwise it should be public...)
EDIT: I've just tried the same thing myself, and seen the same result, except the method is made public. Looks like it's just a fault with Visual Studio - I suggest you create a Connect request for it. It's a relatively rare situation though, I suspect - creating a generic interface which specifies an optional parameter which uses the default value of a type parameter as the value...
Shouldn't this line:
List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(T)) {}
be:
List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(ConcreteWhatever)) {}
public interface IWhatever<T>
{
List<T> Foo(T BarObject = default(T));
}
public class ConcreteWhatever : IWhatever<ConcreteWhatever>
{
public List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(ConcreteWhatever))
{
return null; // replace with proper code
}
}
精彩评论