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);
    }
}
6
  • 5
    public static void MakeRequst<T>(T myObject) where T : class Commented Feb 11, 2016 at 12:18
  • @Dennis Can you explain why this is necessary? Commented Feb 11, 2016 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. Commented Feb 11, 2016 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. Commented Feb 11, 2016 at 12:21
  • THe question is not very clear, what exactly are you trying to do? Commented Feb 11, 2016 at 12:22

1 Answer 1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.