2

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);
Pavel
  • 4,912
  • 7
  • 49
  • 69
  • http://msdn.microsoft.com/en-us/library/system.type.aspx - search for "generic", one of those methods/properties will in all likelihood be what you're looking for. – millimoose Feb 27 '13 at 17:09
  • "So I want to deserialize it and if T is a String instance handle it, in another case I want to throw an exception." Isn't that a little bit in conflict of you class being generic? – bas Feb 27 '13 at 17:17
  • @bas oh, yeah :) I reread my question and realize that is a little bit in conflict... It's not what I really need, but if I know how to do that I'll can do what I really need. – Pavel Feb 27 '13 at 17:40

3 Answers3

5

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

Pavel
  • 4,912
  • 7
  • 49
  • 69
Eduard Dumitru
  • 3,242
  • 17
  • 31
1
var test = new MyGenericType<string>();

var genericTypes = test.GetType().GetGenericArguments();
if (genericTypes.Length == 1 && genericTypes[0] == typeof(string))
{
    // Do deserialization
}
else
{
    throw new Exception();
}
ken2k
  • 48,145
  • 10
  • 116
  • 176
1

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));
millimoose
  • 39,073
  • 9
  • 82
  • 134