I want to fill a generic property with one of the child classes. But I get this error:
Cannot implicitly convert type 'Child1' to 'T'
How can I do it?
For example:
Consider these parent and child classes:
public abstract class Parent
{
public int P1 { get; set; }
public abstract int DoSomething();
}
public class Child1 : Parent
{
public override int DoSomething() { return P1 * 2; }
}
public class Child2 : Parent
{
public override int DoSomething() { return P1 * 3; }
}
And also consider this sample generic class:
public class Sample<T> where T: Parent
{
T ChildObject { get; set; }
public int Test()
{
ChildObject = new Child1 { P1 = 2 }; // Error: Cannot implicitly convert type 'Child1' to 'T'
return ChildObject.DoSomething();
}
}
More explanation:
My mistake was I was trying to initialize child class in the generic class. Following the accepted answer, I should just add new constraint and do ChildObject = new T { P1 = 2 }; and then use ChildObject.DoSomething();.
Solution:
public class Sample<T> where T: Parent, new()
{
T ChildObject { get; set; }
public int Test()
{
ChildObject = new T { P1 = 2 }; // Fixed :)
return ChildObject.DoSomething();
}
}