Martin Ch
Martin Ch

Reputation: 1367

Object deserialization

for deserialization I use working method:

public static bool InvokeDeserializeMethod<T>(ref T o, string serializedObject)
        {
            Type[] typesParameters = new Type[]{typeof(string)};
            MethodInfo methodInfo = typeof(o).GetMethod("Deserialize",typesParameters);
            object[] deserializeMethodParameters = new string [] {serializedObject};
            if (methodInfo != null)
            {
                try
                {
                    o = (T)methodInfo.Invoke(o, deserializeMethodParameters);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

Now I am making copy, paste functions, and I need to deserialize some serialized objects(strings) I cant use this method, because I dont wanna send ref on some existing object, I new object to be created It would be the best If I have a method like:

public static T InvokeDeserializeMethod<T>(string serializedObject)

Is there any way how to achieve it, return object of type T, without having existing object which I would send to method? (Every object I will use with this method contains serialize and deserialize method) Thanks!

Upvotes: 0

Views: 170

Answers (1)

m0sa
m0sa

Reputation: 10940

You can use either one of the Activator.CreateInstance method overloads to create a instance of a known type, if you know it's constructor arguments, or FormatterServices.GetUninitializedObject(Type t) if you don't want to invoke the types constructor on deserialization.

Upvotes: 1

Related Questions