0

I have a method with the following signature:

    private string SerialiazeObj<T>(T obj)
    {
          // Do some work
    }

Now, I have another method which accepts an object and calls the SerializeObj method, as shown below:

    private void callSerializeObj(object obj)
    {
        Type objType = obj.GetType();
        string s = SerialiazeObj<objType>((objType)obj));
    }

The object passed to callSerializeObj can be of any type. Unfortunately, the compiler is giving me this error in the (string s = SerializeObj...) part:

The type or namespace 'objType' could not be found (are you missing an assembly reference).

I don't know if I am calling SerializeObj the correct way. What is the correct way of calling the method with an object which can be of any type?

John Doe
  • 41
  • 2
  • 8

1 Answers1

1

Use as below -

private void callSerializeObj(object obj)
    {
        Type objType = obj.GetType();

       MethodInfo method = this.GetType().GetMethod("SerialiazeObj", BindingFlags.NonPublic | BindingFlags.Instance);
       MethodInfo generic = method.MakeGenericMethod(objType );
       object Result = generic.Invoke(this, new object[] { obj });
    }
Amit
  • 882
  • 6
  • 13