3

Possible Duplicate:
polymorphic resolution of generic parameters in Unity registerType

This is probably obvious. But can someone tell me why this is not valid code? The compiler says it can't convert Class1<string> to Class1<object>. Is upcasting this way not allowed with generics? If so, why not?

namespace Test
{
    public class Tests
    {
        public void Test()
        {            
            Class1<object> objectClass1 = new Class1<string>();
        }
    }
    class Class1<T>
    {
    }
}
Community
  • 1
  • 1
tycom iplex
  • 131
  • 1
  • 8
  • 6
    This is a common question, search for covariance. Here is one thread on the topic: http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example – JohnD Aug 26 '11 at 13:32
  • 1
    Also see [my answer to a similar question](http://stackoverflow.com/questions/4269279/polymorphic-resolution-of-generic-parameters-in-unity-registertype/4269376#4269376) for an explanation of *why* this is not allowed. – cdhowie Aug 26 '11 at 13:35

2 Answers2

0

Have a look at

Covariance and Contravariance in Generics.

Eric Lippert has a series of blog posts on this subject.

Rune
  • 8,340
  • 3
  • 34
  • 47
  • Not sure why this was voted down it addresses the question asked corectly. – Ben Robinson Aug 26 '11 at 13:45
  • @Ben: This may address the question, but it does not *answer* it. It's like asking your professor a question and them telling you that the answer is in the textbook. – Gabe Aug 27 '11 at 05:56
-5

String, Int32, and so on are Struct types, while object, Person and so on are class objects for C#. For this reason, when you create generics, you have to specify a constraint if you plan to use casting features. So, you can use

public void Method<T>() where T : class
or
public void Method<T>() where T : struct
Raffaeu
  • 6,694
  • 13
  • 68
  • 110