You may be able to use extension methods. This method has been called pseudomyxins . Although extension methods are actually static, they pretend to be instances, so you still need a specific instance of T.
It’s also a kind of trick if you want your interface to retain its role as a self-documenting “contract” that determines which methods your T class should have. However, they are type safe (your Foo class will not compile unless you bring IBarExtensions to scope)
//our interface public interface IBar {} // the two static methods are define as extension methods public static class IBarExtensions { public static string someMethod1(this IBar self) { return "my initialization 1"; } public static string someMethod2(this IBar self) { return "my initialization 2"; } } public class Foo<T> where T : IBar, new() { public string value1 {get; private set;} public string value2 {get; private set;} public Foo() { T t = new T(); // we can do this because of the "new()" constraint // in the class definition // Alternatively we could pass an instance of T in // the constructor // public Foo(T t) value1 = t.someMethod1(); value2 = t.someMethod2(); } }
Testing
public class TestBar : IBar {} void Main() { var c = new TestBar(); var t = new Foo<TestBar>(); Console.WriteLine(t.value1); }
source share