Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor requirements on generics parameter?

Tags:

c#

generics

Looking at this question I started thinking about how to handle constructor requirements in C#.

Assume that I have:

T SomeMethod<T>(string s) : where T : MyInterface
{
    return new T(s);
}

I want to set the requirement on T that it can be constructed out of a string, but as far as I know, constructor definitions are not allowed as part of interfaces. Is there a standard way to solve this?

like image 761
Anders Abel Avatar asked Jul 16 '26 06:07

Anders Abel


1 Answers

Add an init method or a property to your interface,

public interface MyInterface
{
    void Init(string s);
    string S { get; set; }
}

T SomeMethod<T>(string s) : where T : MyInterface, new()
{
    var t = new T();
    t.Init(s);

    var t = new T
    { 
        S = s
    };

    return t;
}

As you can't specify arguments to constructor constraints

like image 130
mathieu Avatar answered Jul 18 '26 20:07

mathieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!