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); 
3
  • 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. Commented Feb 27, 2013 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? Commented Feb 27, 2013 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. Commented Feb 27, 2013 at 17:40

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.