I can only cast a contravariant delegate with "as" - c#

I'm trying to cast a contravariant delegate but for some reason I can only do it using the "as" operator.
interface MyInterface { }
delegate void MyFuncType<in InType>(InType input);
class MyClass<T> where T : MyInterface
{
public void callDelegate(MyFuncType<MyInterface> func)
{
MyFuncType<T> castFunc1 = (MyFuncType <T>) func; //Error
MyFuncType<T> castFunc2 = func as MyFuncType<T>;
MyFuncType<T> castFunc3 = func is MyFuncType<T> ? (MyFuncType<T>)func : (MyFuncType<T>)null; //Error
}
}
castFunc2 works fine but castFunc1 and castFunc3 cause the error:
Cannot convert type 'delegateCovariance.MyFuncType<myNamespace.MyInterface>' to myNamespace.MyFuncType<T>'
The MSDN article on the as operator states that castFunc2 and castFunc3 are "equivalent" so I don't understand how only one of them could cause an error. Another piece of this that is confusing me is that changing MyInterface from an interface to a class gets rid of the error.
Can anyone help me understand what is going on here?
Thanks!

Add a constraint such that T must be a class.
class MyClass<T> where T: class, MyInterface
This gives the compiler enough information to know that T is convertible. You don't need the explicit cast either.
Variance only applies to reference types. T is allowed to be a value type without the constraint which breaks the compilers ability to prove that T is compatible for contravariance.
The reason the second statement works is because as actually can perform a null conversion. For example:
class SomeClass { }
interface SomeInterface { }
static void Main(string[] args)
{
SomeClass foo = null;
SomeInterface bar = foo as SomeInterface;
}
Foo is obviously not directly convertable to SomeInterface, but it still succeeds because a null conversion can still take place. Your MSDN reference may be correct for most scenarios, but the generated IL code is very different which means they are fundamentally different from a technical perspective.

Eric Lippert gave a great explanation of this issue in his recent posts: An "is" operator puzzle, part one, An "is" operator puzzle, part two.
Main rationale behind this behavior is following: "is" (or "as") operators are not the same as a cast.
"as" operator can result non-null result event if corresponding cast would be illegal, and this is especially true when we're dealing with type arguments.
Basically, cast operator in your case means (as Eric said) that "I know that this value is of the given type, even though the compiler does not know that, the compiler should allow it" or "I know that this value is not of the given type; generate special-purpose, type-specific code to convert a value of one type to a value of a different type."
Later case deals with value conversions like double-to-integer conversion and we can ignore this meaning in current context.
And generic type arguments are not logical in the first context neither. If you're dealing with a generic type argument, than why you're not stating this "contract" clearly by using generic type argument?
I'm not 100% sure what you're want to achieve, but you can omit special type from your method and freely use generic argument instead:
class MyClass<T> where T : MyInterface
{
public void callDelegate(Action<T> func)
{
}
}
class MyClass2
{
public void callDelegate<T>(Action<T> func)
where T : MyInterface
{
}
}
Otherwise you should use as operator with check for null instead of type check.

Your class says that T implements MyInterface because MyInterface is not a instance type. Therefore, MyFuncType<T> is not guaranteed to be MyFuncType<MyInterface>. It could be MyFuncType<SomeType> and SomeType : MyInterface, but that wouldn't be the same as SomeOtherType : MyInterface. Make sense?

Related

Why my class act so weird with implicit converters [duplicate]

I have a generic class that I'm trying to implement implicit type casting for. While it mostly works, it won't work for interface casting. Upon further investigation, I found that there is a compiler error: "User-defined conversion from interface" that applies. While I understand that this should be enforced in some cases, what I'm trying to do does seem like a legitimate case.
Here's an example:
public class Foo<T> where T : IBar
{
private readonly T instance;
public Foo(T instance)
{
this.instance = instance;
}
public T Instance
{
get { return instance; }
}
public static implicit operator Foo<T>(T instance)
{
return new Foo<T>(instance);
}
}
Code to use it:
var concreteReferenceToBar = new ConcreteBar();
IBar intefaceReferenceToBar = concreteReferenceToBar;
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work
Does anyone know a workaround, or can anyone explain in a satisfactory way why I shuouldn't be able to cast interfaceReferenceToBar implicitly to Foo<IBar>, since in my case it is not being converted, but only contained within Foo?
EDIT:
It looks like covariance might offer salvation. Let's hope the C# 4.0 specification allows for implicit casting of interface types using covariance.
The reason you can't do this is because it is specifically forbidden in the C# language specification:
Source: ECMA-334 Section 15.10.4
A class or struct is permitted to
declare a conversion from a source
type S to a target type T provided all
of the following are true:
...
Neither S nor T is object or an interface-type.
and
User-defined conversions are not
allowed to convert from or to
interface-types. In particular, this
restriction ensures that no
user-defined transformations occur
when converting to an interface-type,
and that a conversion to an
interface-type succeeds only if the
object being converted actually
implements the specified
interface-type.

Type safety in CoVariance and ContraVariance

I am reading C# in Depth from Jon Skeet. Although I have understood the concept of CoVariance and ContraVariance, but I am unable to understand this line:
Well, covariance is safe when SomeType only describes operations that
return the type parameter—and contravariance is safe when SomeType
only describes operations that accept the type parameter.
Can someone please explain with an example for both, why both are type safe in one direction and not in the other direction?
Updated Question:
I still didn't understand from the answers given. I will try to explain my concern using the same example from the book - C# In Depth.
It explains using the following class hierarchy:
COVARIANCE is: Trying to convert from IEnumerable<Circle> to IEnumerable<IShape>, but it is mentioned that this conversion is type safe only when we are performing while returning it from some method, and not type safe when we are passing it as an IN parameter.
IEnumerable<IShape> GetShapes()
{
IEnumerable<Circle> circles = GetEnumerableOfCircles();
return circles; // Conversion from IEnumerable<Circle> to IEnumerable<IShape> - COVARIANCE
}
void SomeMethod()
{
IEnumerable<Circle> circles = GetEnumerableOfCircles();
DoSomethingWithShapes(circles); // Conversion from IEnumerable<Circle> to IEnumerable<IShape> - COVARIANCE
}
void DoSomethingWithShapes(IEnumerable<IShape> shapes) // Why this COVARIANCE is type unsafe??
{
// do something with Shapes
}
CONTRA VARIANCE is: Trying to convert from IEnumerable<IShape> to IEnumerable<Circle>, which is mentioned to be type safe only while performing it when sending it as an IN parameter.
IEnumerable<Circle> GetShapes()
{
IEnumerable<IShape> shapes = GetEnumerableOfIShapes();
return shapes; // Conversion from IEnumerable<IShape> to IEnumerable<Circle> - Contra-Variance
// Why this Contra-Variance is type unsafe??
}
void SomeMethod()
{
IEnumerable<IShape> shapes = GetEnumerableOfIShapes();
DoSomethingWithCircles(shapes); // Conversion from IEnumerable<IShape> to IEnumerable<Circle> - Contra-Variance
}
void DoSomethingWithCircles(IEnumerable<Circle> circles)
{
// do something with Circles
}
Covariance
Covariance is safe when SomeType only describes operations that return the type parameter
The IEnumerable<out T> interface is probably the most common example of covariance. It is safe because it only returns values of type T (well, specifically an IEnumerator<out T> but does not accept any T objects as parameters.
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
This works because IEnumerator<T> is also covariant and only returns T:
public interface IEnumerator<out T> : IDisposable, IEnumerator
{
T Current { get; }
}
If you have a base class called Base and a derived class called Derived, then you can do stuff like this:
IEnumerable<Derived> derivedItems = Something();
IEnumerable<Base> baseItems = derivedItems;
This works because each item in derivedItems is also an instance of Base, so it is perfectly acceptable to assign it the way we just did. However, we cannot assign the other way:
IEnumerable<Base> baseItems = Something();
IEnumerable<Derived> derivedItems = baseItems; // No good!
This isn't safe because there is no guarantee that each instance of Base is also an instance of Derived.
Contravariance
Contravariance is safe when SomeType only describes operations that accept the type parameter
The Action<in T> delegate is a good example of contravariance.
public delegate void Action<in T>(T obj);
It is safe because it only accepts T as a parameter, but doesn't return T.
Contravariance lets you do stuff like this:
Action<Base> baseAction = b => b.DoSomething()
Action<Derived> derivedAction = baseAction;
Derived d = new Derived();
// These 2 lines do the same thing:
baseAction(d);
derivedAction(d);
This works because it is perfectly acceptable to pass an instance of Derived to baseAction. However, it doesn't work the other way around:
Action<Derived> derivedAction = d => d.DoSomething()
Action<Base> baseAction = derivedAction; // No good!
Base b = new Base();
baseAction(b); // This is OK.
derivedAction(b); // This does not work because b may not be an instance of Derived!
This isn't safe because there is no guarantee that an instance of Base will also be an instance of Derived.
Imagine you make an ILogger<in T> interface that knows how to log the details of a T. And let's say you have a Request class and an ExpeditedRequest subclass. Surely an ILogger<Request> should be convertible to an ILogger<ExpeditedRequest>. After all, it can log any request.
Interface ILogger<in T> where T: Request {
void Log(T arg);
}
Now imagine another interface IRequestProducer<out T> that gets the next request in some queue. There are different sources of requests in your system, and of course, some of them can still have different subclasses. In this case, we can't rely on converting an IRequestProducer<Request> to an IRequestProducer<ExpeditedRequest> since it could produce a non-expedited request. But the reverse conversion would work.
Interface IRequestProducer<T> where T: Request {
T GetNextRequest();
}
I understood after reading from MSDN, the following two pages:
https://msdn.microsoft.com/en-us/library/dd469484.aspx
https://msdn.microsoft.com/en-us/library/dd469487.aspx
Actually, I think it will become clear from the book also when I will reach the C# 4 part of the book that will explain in and out keywords with Type Parameters of Generics. Right now, I was reading the Limitations of Generics in C# in the C# 1 part of book.
The statement that I wanted to understand was this:
Well, covariance is safe when SomeType only describes operations that
return the type parameter—and contravariance is safe when SomeType
only describes operations that accept the type parameter.
Besides being safe, it is also not possible to write the interface method in other direction as compiler will complain, as written in the above two pages on msdn:
A type can be declared contravariant in a generic interface or delegate if it is used only as a type of method arguments and not used as a method return type.
In a generic interface, a type parameter can be declared covariant if it satisfies the following conditions:
The type parameter is used only as a return type of interface methods and not used as a type of method arguments.
There are now two points, that made me confuse about the statement:
First , I was misunderstanding the statement itself - I was thinking that Covairance is safe only when an instance of Inteface<T> itself is returned from some method rather than passed as an input to some method. However, it is regarding the type parameter T and interface method. Same for ContraVariance.
Second, Now When I have understood what this statement means - that it is regarding passing/returning the generic type parameter T to/from interface methods. I wanted to know why it is Type Safe only while returning T from interface method in Covariance and why it is Type Safe only while passing T as input to interface method in ContraVariance.
Why it is Type Safe only while returning T in CoVariance:
interface IBase<out T>
{
T Return_T(); // Valid and Type Safe
void Accept_T(T input) // Invalid and Type UnSafe
}
class Sample<T> : IBase<T> { }
class BaseClass {}
class DerivedClass : BaseClass
{}
IBase<BaseClass> ibase = new Sample<BaseClass>();
IBase<DerivedClass> iderived = new Sample<DerivedClass>();
ibase = iderived; // Can be assinged because `T` is Covariant
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
ibase.Return_T(); // At runtime, this will return `DerivedClass` which can be assinged to variable of both base and derived class and is type safe
ibase.Accept_T(b); // The compiler will accept this statement, because at compile time, it accepts an instance of `BaseClass`, but at runtime, it actually needs an instance of `DerivedClass`. So, we are eventually assigning an instance of `BaseClass` to `DerivedClass` which is type unsafe.
Why it is Type Safe only while passing T as an input parameter in ContraVariance:
interface IBase<in T>
{
T Return_T(); // Invalid and Type UnSafe
void Accept_T(T input) // Valid and Type Safe
}
class Sample<T> : IBase<T> { }
class BaseClass {}
class DerivedClass : BaseClass
{}
IBase<BaseClass> ibase = new Sample<BaseClass>();
IBase<DerivedClass> iderived = new Sample<DerivedClass>();
iderived = ibase; // Can be assinged because `T` is Contravariant
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
iderived.Accept_T(d); // This is Type Safe, because both at compile time and runtime, either instance of `DerivedClass` can be assinged to `BaseClass` or instance of `BaseClass` can be assinged to `BaseClass`
DerivedClass d2 = iderived.Return_T(); // This is type unsafe, because this statement is valid at compile time, but at runtime, this will return an instance of `BaseClass` which is getting assinged to `DerivedClass`

Structs, Interfaces and Boxing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it safe for structs to implement interfaces?
Take this code:
interface ISomeInterface
{
public int SomeProperty { get; }
}
struct SomeStruct : ISomeInterface
{
int someValue;
public int SomeProperty { get { return someValue; } }
public SomeStruct(int value)
{
someValue = value;
}
}
and then I do this somewhere:
ISomeInterface someVariable = new SomeStruct(2);
is the SomeStruct boxed in this case?
Jon's point is true, but as a side note there is one slight exception to the rule; generics. If you have where T : ISomeInterface, then this is constrained, and uses a special opcode. This means the interface can be used without boxing. For example:
public static void Foo<T>(T obj) where T : ISomeInterface {
obj.Bar(); // Bar defined on ISomeInterface
}
This does not involve boxing, even for value-type T. However, if (in the same Foo) you do:
ISomeInterface asInterface = obj;
asInterface.Bar();
then that boxes as before. The constrained only applies directly to T.
Yes, it is. Basically whenever you need a reference and you've only got a value type value, the value is boxed.
Here, ISomeInterface is an interface, which is a reference type. Therefore the value of someVariable is always a reference, so the newly created struct value has to be boxed.
I'm adding this to hopefully shed a little more light on the answers offered by Jon and Marc.
Consider this non-generic method:
public static void SetToNull(ref ISomeInterface obj) {
obj = null;
}
Hmm... setting a ref parameter to null. That's only possibly for a reference type, correct? (Well, or for a Nullable<T>; but let's ignore that case to keep things simple.) So the fact that this method compiles tells us that a variable declared to be of some interface type must be treated as a reference type.
The key phrase here is "declared as": consider this attempt to call the above method:
var x = new SomeStruct();
// This line does not compile:
// "Cannot convert from ref SomeStruct to ref ISomeInterface" --
// since x is declared to be of type SomeStruct, it cannot be passed
// to a method that wants a parameter of type ref ISomeInterface.
SetToNull(ref x);
Granted, the reason you can't pass x in the above code to SetToNull is that x would need to be declared as an ISomeInterface for you to be able to pass ref x -- and not because the compiler magically knows that SetToNull includes the line obj = null. But in a way that just reinforces my point: the obj = null line is legal precisely because it would be illegal to pass a variable not declared as an ISomeInterface to the method.
In other words, if a variable is declared as an ISomeInterface, it can be set to null, pure and simple. And that's because interfaces are reference types -- hence, declaring an object as an interface and assigning it to a value type object boxes that value.
Now, on the other hand, consider this hypothetical generic method:
// This method does not compile:
// "Cannot convert null to type parameter 'T' because it could be
// a non-nullable value type. Consider using 'default(T)' instead." --
// since this method could take a variable declared as, e.g., a SomeStruct,
// the compiler cannot assume a null assignment is legal.
public static void SetToNull<T>(ref T obj) where T : ISomeInterface {
obj = null;
}
The MSDN documentation tells us that structs are value, not reference types. They are boxed when converting to/from a variable of type object. But the central question here is: what about a variable of an interface type? Since the interface can also be implemented by a class, then this must be tantamount to converting from a value to a reference type, as Jon Skeet already said, therefore yes boxing would occur. More discussion on an msdn blog.

Delegate Covariance Confusion Conundrum!

Why does this not work? Do I not understand delegate covariance correctly?
public delegate void MyDelegate(object obj)
public class MyClass
{
public MyClass()
{
//Error: Expected method with 'void MyDelegate(object)' signature
_delegate = MyMethod;
}
private MyDelegate _delegate;
public void MyMethod(SomeObject obj)
{}
}
Correct - you don't understand covariance correctly - yet :) Your code would work if you had the same types but as return values, like this:
public delegate object MyDelegate()
public class MyClass
{
public MyClass()
{
_delegate = MyMethod;
}
private MyDelegate _delegate;
public SomeObject MyMethod() { return null; }
}
That would demonstrate covariance. Alternatively, you can keep it as parameters but switch the types around:
public delegate void MyDelegate(SomeObject obj)
public class MyClass
{
public MyClass()
{
_delegate = MyMethod;
}
private MyDelegate _delegate;
public void MyMethod(object obj) {}
}
This now demonstrates contravariance.
My rule of thumb is to ask myself, "given the delegate, what could I do with it? If I can pass in an argument which would break the method, the conversion should have failed. If the method can return something which would break the caller, the conversion should have failed."
In your code, you could have called:
_delegate(new object());
At that point, poor MyMethod has a parameter which is meant to be of type SomeObject, but is actually of type object. This would be a Very Bad Thing, so the compiler stops it from happening.
Does that all make more sense?
Arguments are contravariant, return types are covariant. If the delegate were to be called with an object that is not an instance of SomeObject, you'd have a typing error. On the other hand, returning SomeObject from a routine wrapped in a delegate that returns object is fine.
You need to use a generic.
EDIT: Why? Because as another poster
noted, Object and SomeObject do not
equate to the same thing as Object may
not be SomeObject. This is the whole
point of Generics in the language.
public delegate void MyDelegate<T>(T obj)
public class MyClass
{
public MyClass()
{
_delegate = MyMethod;
}
private MyDelegate<SomeObject> _delegate;
public void MyMethod(SomeObject obj)
{
}
}
The MyDelegate type declares that you can pass any kind of object in. However, MyMethod only takes objects of type SomeObject. What happens if I try to invoke the delegate passing a different kind of object: _delegate("a string object")? According to the declaration of MyDelegate, this should be allowed, but your function MyMethod can't actually receive a string argument.
From the MSDN link you provided
Covariance permits a method to have a
more derived return type than what is
defined in the delegate.
Contravariance permits a method with
parameter types that are less derived
than in the delegate type.
You're attempting to use a more derived parameter type which isn't supported (although .NET 4.0 probably will since this has sorted out many covariance/contravariance issues).
Covariance and Contravariance is about understanding the Is-a-Principle of inheritance.
In both, covariance and contravariance, s.th. is "passed along", either as return value or as an argument to the delegate method. That which is "passed along" has to be "caught" in a receptacle. In C# – or programming jargon as such – we use the word bucket for what I called receptacle. Sometimes you have to fall back to other words in order to catch the meaning of commonly used jargon words.
Anyway, if you understand inheritance, which most likely any reader here will, then the only thing to pay attention to is that the receptacle, i. e. the bucket used for catching has to be of the same type or less derived type than that which is being passed – this being true for both covariance and contravariance.
Inheritance says you can catch a bird in an animal bucket because the bird is an animal. So if a parameter of a method has to catch a bird you could catch it in an animal bucket (a parameter of type animal), which then is contravariance.
And if your method, i.e. your delegate returns a bird, then the "bucket" also can be a of type bird or less derived (of a parent type) meaning the variable where you catch the return value of the method has to be of the same or less derived type than the return value.
Just switch your thinking to discriminate between that which is being passed and that which catches as then all complexity about covariance and contravariance dissolves nicely. Then you realize that the same principle is at work. It is just that inheritance cannot be violated as it flows only one way.
And the compiler is so smart that when you cast the bucket in the more specialized type (again, and as need be) that then and only then you get all the specialized methods back that were added into the more derived class. That is the beauty of it. So it is catch, cast and use what you have and perhaps need.

implicit operator using interfaces

I have a generic class that I'm trying to implement implicit type casting for. While it mostly works, it won't work for interface casting. Upon further investigation, I found that there is a compiler error: "User-defined conversion from interface" that applies. While I understand that this should be enforced in some cases, what I'm trying to do does seem like a legitimate case.
Here's an example:
public class Foo<T> where T : IBar
{
private readonly T instance;
public Foo(T instance)
{
this.instance = instance;
}
public T Instance
{
get { return instance; }
}
public static implicit operator Foo<T>(T instance)
{
return new Foo<T>(instance);
}
}
Code to use it:
var concreteReferenceToBar = new ConcreteBar();
IBar intefaceReferenceToBar = concreteReferenceToBar;
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar;
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work
Does anyone know a workaround, or can anyone explain in a satisfactory way why I shuouldn't be able to cast interfaceReferenceToBar implicitly to Foo<IBar>, since in my case it is not being converted, but only contained within Foo?
EDIT:
It looks like covariance might offer salvation. Let's hope the C# 4.0 specification allows for implicit casting of interface types using covariance.
The reason you can't do this is because it is specifically forbidden in the C# language specification:
Source: ECMA-334 Section 15.10.4
A class or struct is permitted to
declare a conversion from a source
type S to a target type T provided all
of the following are true:
...
Neither S nor T is object or an interface-type.
and
User-defined conversions are not
allowed to convert from or to
interface-types. In particular, this
restriction ensures that no
user-defined transformations occur
when converting to an interface-type,
and that a conversion to an
interface-type succeeds only if the
object being converted actually
implements the specified
interface-type.

Categories

Resources