Binary deserializing generic object in C#

2k Views Asked by At

I have a generic class which can be serialized:

MyOwnGenericClass<T>

So I want to deserialize it and if T is a String instance handle it, in another case I want to throw an exception.

How to know type of generic contains in MyOwnGenericClass<T> while deserializing? To what class I have to cast following code?

new BinaryFormatter().Deserialize(fileStrieam);
3

There are 3 best solutions below

0
On BEST ANSWER

That's really easy. Just use object like so:

object obj = new BinaryFormatter().Deserialize(fileStrieam);

and then do what you said you would do:

if (!(obj is MyOwnGenericClass<string>))
    throw new Exception("It was something other than MyOwnGenericClass<string>");
else {
    MyOwnGenericClass<string> asMyOwn_OfString = obj as MyOwnGenericClass<string>;

    // do specific stuff with it
    asMyOwn.SpecificStuff();
}

So you're not checking if T is a string. You're checking more than that: You're checking if obj is a MyOwnGenericClass< string >. Nobody said it will always be a MyOwnGenericClass< something > and our only headache is to find what that something is.

You can send bools, strings, ints, primitive arrays of int, even a StringBuilder. And then there's your entourage: you could send MyOwnGenericClass< int >, MyOwnGenericClass< string > (and this is the only one you accept).

0
On
var test = new MyGenericType<string>();

var genericTypes = test.GetType().GetGenericArguments();
if (genericTypes.Length == 1 && genericTypes[0] == typeof(string))
{
    // Do deserialization
}
else
{
    throw new Exception();
}
0
On

You can use Type.GetGenericArguments() to get the actual values of generic arguments a type was created with at runtime:

class MyGeneric<TValue> {}

object stringValue = new MyGeneric<string>();
object intValue = new MyGeneric<int>();

// prints True
Console.WriteLine(stringValue.GetType().GetGenericArguments()[0] == typeof(string));
// prints False
Console.WriteLine(intValue.GetType().GetGenericArguments()[0] == typeof(string));