1

I have function like this

public static void serialize<T>(T serializeObject){
    //this is the trouble
    SerializableEntity<T> entity = new SerializableEntity<T>(serializeObject);
}

How can I make that in using generics inside of generics? How to accomplish this?

UPDATE

Here the compiler error:

Error image

John Willemse
  • 6,608
  • 7
  • 31
  • 45
mrhands
  • 1,473
  • 4
  • 22
  • 41

2 Answers2

8

There is nothing wrong per-se with the code you have: that compiles fine:

class SerializableEntity<T> {
    public SerializableEntity(T obj) { }
}
static class P {
    public static void serialize<T>(T serializeObject) {
        //this is fine...
        SerializableEntity<T> entity =
            new SerializableEntity<T>(serializeObject);
    }
    static void Main() { /*...*/ }
}

So the real question is: what does the compiler say? The most obvious one would be if it says something like:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'SerializableEntity<T>'

which is a "constraint" violation; if that is what you are seeing you need to add the constraints to serialize<T> to prove to the compiler that the constraints are always satisfied. For example, if SerializableEntity<T> is declared as:

class SerializableEntity<T> where T : class
{...}

then you simply transfer that constraint to the method:

public static void serialize<T>(T serializeObject) where T : class
{...}

Note that other constraints are possible, including:

  • : class
  • : struct
  • : SomeBaseType
  • : ISomeInterface
  • : new()
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    @mrhands advice for next time: include the exact compiler error message (ideally copied as text) in the question. Or even better: copy the error message into *google* first, and see what the internet says... – Marc Gravell May 24 '13 at 07:18
1

You probably have different constraints on T in the method and in the class.

Take in mind that if the class says:

where T  : class, IDisposable 

Then the method has to have at least the same where

Adam Tal
  • 5,911
  • 4
  • 29
  • 49