I have a class that has a Generic type ‘G’
In my class model i have
public class DetailElement : ElementDefinition
Let’s say i have a method like this
public void DoSomething<G>(G generic) where G : ElementDefinition { if (generic is DetailElement) { ((DetailElement)generic).DescEN = 'Hello people'; //line 1 ////// ElementDefinition element = generic; ((DetailElement)element).DescEN = 'Hello again'; //line 3 ////// (generic as DetailElement).DescEN = 'Howdy'; //line 5 } else { //do other stuff } }
Compiler reports one error in line 1:
Cannot convert type 'G' to 'DetailElement'
But line 3 works fine. I can workaround this issue by doing the code written in line 5.
What i would like to know is why does the compiler reports the error in line 1 and not the one in line 3, given that, as far as i know, they are identical.
edit: I am afraid i might be missing some important piece of the framework logic
edit2: Although solutions for the compiler error are important, my question is about why the compiler reports an error on line 1 and not in line 3.
If
Gwas constrained to be aDetailElement(where G : DetailElement) then you can go ahead and castGto ElementDefinition, i.e., ‘(ElementDefinition) generic‘. But becauseGmight be another subclass ofElementDefinitionother thanDetailElementat run-time it won’t allow it at compile-time where the type is unknown and unverifiable.In line 3 the type you cast from is known to be an
ElementDefinitionso all you’re doing is an up-cast. The compiler doesn’t know if it will be a succcesful cast at run-time but it will trust you there. The compiler is not so trusting for generics.The
asoperator in line 5 might also return null and the compiler doesn’t statically check the type to see if it’s safe in that case. You can useaswith any type, not just ones that are compatible withElementDefinition.From Can I Cast to and from Generic Type Parameters? on MSDN: