Targeting .NET 4.0, I'm trying to build the following classes:
public class ConfigurationElementCollection<TElement, TParent>
where TElement : ParentedConfigElement<TParent>, new()
where TParent : class
{
public TParent ParentElement { get; set; }
protected ConfigurationElement CreateNewElement()
{
//**************************************************
//COMPILER GIVES TYPE CONVERSION ERROR ON THIS LINE!
//**************************************************
return new TElement { ParentCollection = this };
}
}
public class ParentedConfigElement<TParent> : ConfigurationElement where TParent : class
{
internal ConfigurationElementCollection<ParentedConfigElement<TParent>, TParent>
ParentCollection { get; set; }
protected TParent Parent
{
get
{
return ParentCollection != null ? ParentCollection.ParentElement : null;
}
}
}
As the code comment above indicates, the compiler gives an error:
Cannot implicitly convert type 'Shared.Configuration.ConfigurationElementCollection<TElement, TParent>' to 'Shared.Configuration.ConfigurationElementCollection<Shared.Configuration.ParentedConfigElement,TParent>
I don't expect this error, because the compiler also knows that TElement
is a Shared.Configuration.ParentedConfigElement<TParent>
due to the generic type constraint I specified.
Still, I figure I will expressly cast the type to get past this issue:
(ConfigurationElementCollection<ParentedConfigElement<TParent>,TParent>) this;
Unfortunately, I get the same compiler error. Why is this happening? What did I do wrong? And without resorting to dynamic
types, what can I do to fix this?