Walkingsteak
Walkingsteak

Reputation: 349

Setting the generic parameter from an object's variable

Say I have a number of different classes that implement this interface:

public interface IRequest
{
    Type ResponseType { get; }
}

Where the idea is that each Request-class specifies the Type of the reponse it would receive.

And I have a class for serializing/deserializing, where the deserialize-method signature is so:

public static T Deserialize<T>(byte[] data) where T : IRequest
{ ... }

How can I call Deserialize, and use the ResponseType variable as the generic parameter?

var request = new SomeRequest() // object which implements IRequest
byte[] receivedData = myNetworkService.SendRequest(request.Serialize());
var response = MyBinarySerializer.Deserialize<request.ResponseType>(receivedData);

Or is there another way to go about this? The class I am using for serializing/deserializing is 3rd party, so I cannot change it. Its Deserialize<T>() needs to be called with the generic parameter T

Upvotes: 1

Views: 78

Answers (2)

Kaido
Kaido

Reputation: 4001

The generic parameter is a design time type, where the property is a runtime type. You can't use a runtime type as a design time type, but there should be an overload of Deserialize that takes a type:

object deserialisedObject =  Deserialise(Type t, Object o);
if(deserialisedObject is MyType)
{
    var property = ((MyType)deserialisedObject).MyProperty;
}

Upvotes: 0

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

You can add another overload of Deserialize which accepts a Type argument. Then you can delegate the generic call to that as well.

public static T Deserialize<T>(byte[] data) where T : IRequest
{ 
    return Deserialize(typeof(T), byte[] data) as T;
}

public static object Deserialize(Type, byte[] data)
{ 
   ...
}

Upvotes: 1

Related Questions