1

How I can do something like this? I have found How do I use reflection to call a generic method? but not sure that this is my case.

public class XmlSerializer 
{
    public string Serialize<T>(T obj) where T : class
    {
        return string.Empty;
    }
}


class Program
{
    static void Main(string[] args)
    {
        MakeRequst<string>("value");
    }


    public static void MakeRequst<T>(T myObject)
    {
        var XmlSerializer = new XmlSerializer();
        XmlSerializer.Serialize<T>(myObject);
    }
}
Community
  • 1
  • 1
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
  • 5
    `public static void MakeRequst(T myObject) where T : class` – Dennis Feb 11 '16 at 12:18
  • @Dennis Can you explain why this is necessary? – Maarten Feb 11 '16 at 12:19
  • 1
    @Maarten, Because the generic argument on the `Serialize()` method is constrained to reference types. When `MakeRequst()` calls it with an *unconstrained* `T`, the constraint cannot be enforced. – haim770 Feb 11 '16 at 12:21
  • 2
    Shouldn't there be a compiler error? This error should be posted here and it also, I think, tells you what is wrong. – usr Feb 11 '16 at 12:21
  • THe question is not very clear, what exactly are you trying to do? – David Pine Feb 11 '16 at 12:22
  • @haim770 **I** know the reason why, but obviously the OP didn't know that. And that is exactly what he needed to know. – Maarten Feb 11 '16 at 12:22

1 Answers1

13

Generic method, that calls another generic method, can't be less constrained, than the method being called:

public class Foo
{
    public void Bar1<T>() where T : class {}
    public void Bar2<T>() where T : class
    {
        Bar1<T>(); // same constraints, it's OK
    } 

    public void Bar3<T>() where T : class, ISomeInterface
    {
        Bar1<T>(); // more constraints, it's OK too
    }

    public void Bar4<T>()
    {
        Bar1<T>(); // less constraints, error
    }
}

Here Bar4 method breaks Bar1 constraints, because it allows you to pass value type as generic argument, but this is not allowed for Bar1 method.

Dennis
  • 37,026
  • 10
  • 82
  • 150