mrhands
mrhands

Reputation: 1533

Generics method inside of generics method

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

Upvotes: 1

Views: 245

Answers (2)

Adam Tal
Adam Tal

Reputation: 5961

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

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062745

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()

Upvotes: 8

Related Questions