C# Generics

G

Guest

Can anyone tell me what is wrong with this:

namespace Test
{
public class A
{}

public class B : A
{}

public class G<T> where T : A
{}

public class F : G<B>
{}

public class Test
{
private G<A> a = new F();
private G<A> b = new G<B>();
}
}

To me that should be OK but I think I've missed something.

Thanks in Advance

Chris
 
C

Christof Nordiek

Hi uasking,

see inline,

uAsking said:
Can anyone tell me what is wrong with this:

namespace Test
{
public class A
{}

public class B : A
{}

public class G<T> where T : A
{}

public class F : G<B>
{}

public class Test
{
private G<A> a = new F();
private G<A> b = new G<B>();

You can't cast here. Generics in C# don't support covariance nor
constravariance. So G<B> and G<A> here simply are different types. With no
assignment relation. This prevents exceptions like ArrayCovirianceException,
as well as runtime type-checking.

Christof
 
B

Ben Voigt [C++ MVP]

uAsking said:
Can anyone tell me what is wrong with this:

namespace Test
{
public class A
{}

public class B : A
{}

public class G<T> where T : A
{}

public class F : G<B>
{}

public class Test
{
private G<A> a = new F();
private G<A> b = new G<B>();
}
}

To me that should be OK but I think I've missed something.

A G<B> is not a (subtype of) G<A>, because it fails the substitutability
test.

Add a member function (method) to G<T> as follows:

void DoIt(T t) { }

Now, clearly F.DoIt requires a B. An A simply will not suffice. So F
cannot be used everywhere a G<A> can be used.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top