Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

C# Call Generic method from Generic method

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

Upvotes: 1

Views: 4887

Answers (1)

Dennis
Dennis

Reputation: 37760

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.

Upvotes: 13

Related Questions