views:

61

answers:

1
public interface IMyControl<in T> where T : ICoreEntity
{
    void SetEntity(T dataObject);
}

public class MyControl : UserControl, IMyControl<DataObject>   // DataObject implements ICoreEntity
{
    void SetEntity(T dataObject);
}

All fine so far, but why does this create null?

var control = LoadControl("~/Controls/MyControl.ascx"); // assume this line works
IMyControl<ICoreEntity> myControl = control;

myControl is now null...

+2  A: 

You cannot have dataObject as parameter for this to work. Methods could only return it.

public interface ICoreEntity { }
public class DataObject: ICoreEntity { }

public interface IMyControl<out T> where T : ICoreEntity
{
    T GetEntity();
}

public class MyControl : IMyControl<DataObject>   // DataObject implements ICoreEntity
{
    public DataObject GetEntity()
    {
        throw new NotImplementedException();
    }
}

Now you can:

MyControl control = new MyControl();
IMyControl<ICoreEntity> myControl = control;
Darin Dimitrov
Isn't that covariance not contravariance? I thought they introduced the out keyword in order for this to work? It compiles anyway
Paul
Yes this is covariance, but the way you intend to use it is covariance. Take a look here: http://msdn.microsoft.com/en-us/library/ee207183.aspx
Darin Dimitrov