Generics confusion

J

joseph_gallagher

Hi,

I've been playing with generics and I was wondering if anyone could
tell me why the following doesnt work, and if there is another way to
do it

public class A<T> where T : B, new() {
public B Get() {
B b = new B();
b.X = this;
return b;
}
}

public class B {
public A<B> X { set { } }
}

basicaly class A<T> knows that T is inherited from type B, but type B
contains a property X of type A<B> and I'd like to be able to set this
property from class A<T>, which I would have though should work since
the compiler knows T is of type B, I cant even cast this to A<B> as a
workaround.

Any help appreciated
 
K

Kevin Spencer

public class A<T> where T : B, new() {
public B Get() {
B b = new B();
b.X = this;
return b;
}
}

public class B {
public A<B> X { set { } }
}

public class C : B
{
}

What happens when you create an instance of A<C>?

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
B

Ben Voigt [C++ MVP]

Hi,

I've been playing with generics and I was wondering if anyone could
tell me why the following doesnt work, and if there is another way to
do it

public class A<T> where T : B, new() {
public B Get() {
B b = new B();
b.X = this;
return b;
}
}

public class B {
public A<B> X { set { } }
}

basicaly class A<T> knows that T is inherited from type B, but type B
contains a property X of type A<B> and I'd like to be able to set this
property from class A<T>, which I would have though should work since
the compiler knows T is of type B, I cant even cast this to A<B> as a
workaround.

Your problem is that generics aren't covariant, so
T : B doesn't imply A<T> : A<B>

For example:
Add a field Beta to A<T> of type T, and assume that B.X is implemented by a
backing field and has a getter as well. Now inside A<T>.Get(), you could
set b.X.Beta = new B(); Now this.Beta has dynamic type B, but is required
to have dynamic type T. Type-safety therefore requires that the compiler
reject the line "b.X = this".
 

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