Why do I get a type conversion compile error for the following piece of code?
I have quite a few instances of derived Def/View classes in my project. All of them have some code base, say persistence, retrieval etc. I thought by writing a helper class using generics I could achieve maintainability of this common code base.
However I get 'Type Conversion' compilation error in the DoSomeStuff method on the line that assigns the view to def. I have taken care to write implicit cast conversion for all of base and derived classes.
Note that Def & View classes intentionally do not derive from some common class. Additionally I always want to convert only from View to Def and never the other way round, hence only my View classes have the implicit conversion defined on them.
I did try to follow Eric Lipert's discussion on Covariance and Contravariance, but got quite muddled up in my head as he progressed with his examples. Any help with this problem is greatly appreciated.
public class BaseDef
{
public int Id { get; set; }
}
public class DerivedDef : BaseDef
{
public string Name { get; set; }
public DerivedDef()
: base()
{
}
public DerivedDef(BaseDef bd)
{
this.Id = bd.Id;
}
}
public class BaseView
{
public int Id { get; set; }
public BaseView()
{
}
public BaseView(BaseDef bd)
{
Id = bd.Id;
}
public BaseDef ToBaseDef()
{
return new BaseDef { Id = this.Id };
}
public static implicit operator BaseView(BaseDef bd)
{
return new BaseView(bd);
}
public static implicit operator BaseDef(BaseView bv)
{
return bv.ToBaseDef();
}
}
public class DerivedView : BaseView
{
public string Name { get; set; }
public DerivedView()
: base()
{
}
public DerivedView(DerivedDef dd)
: base(dd)
{
Name = this.Name;
}
public DerivedDef ToDerivedDef()
{
return new DerivedDef(this)
{
Name = this.Name,
};
}
}
public class SomeHelper<Tdef, Tview>
where Tdef : BaseDef
where Tview : BaseView
{
public void DoSomeStuff(Tview vm)
{
Tdef df = vm; // this line give a compile error 'Cannot convert type 'Tview' to 'Tdef'
// work with df from here on
}
}
dfas typeTdefrather than usingvar? (I suspect you could significantly simplify your example, by the way.) - Jon Skeet