I am wondering if it is possible to use the type of one variable to set as the type of another generic variable?
For example, say I have this code:
public class Foo: IBar<ushort>
{
public FooBar()
{
Value = 0;
}
public ushort Value { get; private set; }
}
I also have this class:
public class FooDTO<TType> : IBar<TType>
{
public TType Value { get; private set; }
}
In these examples, in the interface for IBar has the property
TType Value;
Then in my code I have this
var myFoo = new Foo();
var fooDataType = myFoo.Value.GetType();
//I know this line of code does not compile, but this is what I am looking to be able to do
var myFooDTO= new FooDTO<fooDataType>();
Is what I am looking for possible? Would it be too slow for high use code (because of using reflection.
You can do this via Reflection, by using Type.MakeGenericType.
This will have some overhead due to reflection, so you'd need to profile it to see if that will be an issue for you.
Why not use Method type inference:
public class FooDTO<TType> {
public TType Value { get; private set; }
}
public class Foo : FooDTO<ushort> { }
static FooDTO<T> GetTypedFoo<T>(T Obj) {
return new FooDTO<T>();
}
static void Main(string[] args) {
Foo F = new Foo();
var fooDTO = GetTypedFoo(F.Value);
}
Always when I read "generic" and "runtime" in one sentence, I always thing "bad design" or "doesnt understant what generic means". Possibly both.
Generic parameter is integral part of the type. So saying "Generate Generic Type At Runtime" is same as "Generate Foo class at runtime". You are either looking for reflection or change design of your algorithm.
Also var keyword is not going to help you in this case. Forget about it.
You're looking for compile-time reflection, a feature that C# doesn't have. So if you're looking for performance optimizations, the solutions are worse than the problem.
D does have this feature, though; you can easily write
int x = 0;
typeof(x) y = x + 2;
or even much more complicated expressions in D, and it's all evaluated at compile-time.
The core of what you want is:
var type = typeof(FooDTO<>).MakeGenericType(fooDataType);
object obj = Activator.CreateInstance(type);
however, you'll notice that this is reflection, and pretty much ties you to object. The usual workaround to this is to have access to a non-generic version of the API, so that you can work with object - for example (with the addition of a non-generic IBar):
IBar bar = (IBar)Activator.CreateInstance(type);
You can of course move the runtime/generics hit higher up - perhaps into a generic method; then everything in the generic method can use T, and you can use MakeGenericMethod to execute that method in the context of a particular T known only at runtime.
Related
I saw this interesting question which talks about T declaration at the class level and the same letter T ( different meaning) at the method level.
So I did a test.
static void Main(string[] args)
{
var c = new MyClass<int>(); //T is int
c.MyField = 1;
c.MyProp = 1;
c.MyMethod("2");
}
public class MyClass<T>
{
public T MyField;
public T MyProp { get; set; }
public void MyMethod<T>(T k)
{
}
}
As Eric said , the compiler does warn.
But Hey , what happened to type safety ? I assume there is a type safety at the Method level but what about the global context of the class where T already has been declared.
I mean if someone would have asked me , I would guess there should be an error there and not a warning.
Why the compiler allows that? ( I would love to hear a reasonable answer)
Interesting question. Type safety is preserved here. Behaviour is alike global and local variables. In MyMethod type T is unambiguous. We can also create and return new instance of MyClass as follows:
public class MyClass<T>
{
public T MyField;
public T MyProp { get; set; }
public MyClass<T> MyMethod<T>(T k)
{
return new MyClass<T>();
}
}
The program:
static void Main()
{
var c = new MyClass<int>(); //T is int
c.MyField = 1;
c.MyProp = 1;
var myClass = c.MyMethod("2");
myClass.MyField = "2";
myClass.MyField = "4";
}
There is no compilation error and it shouldn't be, because type safety is preserved. Program can be compiled. There is no ambiguity.
The warning should be there, because T overrides its class level counterpart and there is no simple way in MyMethod to obtain that global T. It also obscures legibility.
MSDN says about flexibility and good practice in Generic Methods (C# Programming Guide):
If you define a generic method that takes the same type parameters as the containing class, the compiler generates warning CS0693 because within the method scope, the argument supplied for the inner T hides the argument supplied for the outer T. If you require the flexibility of calling a generic class method with type arguments other than the ones provided when the class was instantiated, consider providing another identifier for the type parameter of the method.
This is not a type-safety issue. It is only a readability issue - that's why it's just a warning. (Also, T hides the outer T.)
If change MyMethod() to:
public void MyMethod<T>(T k)
{
Console.WriteLine(typeof(T).FullName);
}
It'll print out System.String for your sample code, proving that it is getting the correct type.
Long story short, I would like to be able to store generics using different type parameters in an array, by using a parent type to all the types used. MSDN mentioned it was impossible, as generics were invariant types, but a comment stated that this changed since the 4.0 framework.
Here is a basic example of what I would like to do:
public class Animal
{
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}
public class MyGeneric<T>
{ }
public class MyInheritedGeneric<T> : MyGeneric<T>
{ }
static void Main(string[] args)
{
MyGeneric<Animal>[] myGenericArray = new MyGeneric<Animal>[]
{
new MyGeneric<Dog>(),
new MyInheritedGeneric<Cat>()
};
}
This returns the similar errors:
Cannot implicitly convert type
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Dog>' to
'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Cannot implicitly convert type
'InheritanceTest.Program.MyInheritedGeneric<InheritanceTest.Program.Cat>'
to 'InheritanceTest.Program.MyGeneric<InheritanceTest.Program.Animal>'
Is there any way to store generics in an array using the parent class of the type, or is this simply impossible? I really hope it is possible, otherwise it will make my program a nightmare...
EDIT: A bit more context!
I am making classes to generate enemies in a game. I call them Templates (nothing to do with actual template classes, I could very well have called them Blueprints or Factories). An enemy constructor takes in a Template, which it uses to determine its own values. When the game loads, the templates are used to generate all enemies, using their Generate() function, which returns an array of the corresponding type they are assigned to produce. All the objects to be created with a template are to have a constructor taking a template as their sole parameter.
public class Template<T>
{
protected static Random random = new Random();
protected int _amount;
public int Amount
{
get { return _amount; }
}
public virtual T CreateInstance()
{
return (T)Activator.CreateInstance(typeof(T), this);
}
public virtual T[] Generate()
{
T[] objects = new T[Amount];
for (int i = 0; i < Amount; ++i)
objects[i] = CreateInstance();
return objects;
}
}
Here is a summary of the BasicZombie.cs file, which contains the actual enemy class and the template.
class Tpl_BasicZombie : Tpl_Enemy<BasicZombie>
{
public Tpl_BasicZombie()
{
_hp = 4;
_speed = 3;
_amount = 10;
}
}
class BasicZombie : GroundEnemy
{
public BasicZombie(Tpl_BasicZombie template)
: base(template, TextureManager.Get("zombie_base"), 1, 8)
{ }
public void StuffHappens()
{ }
}
When loading the game, I would like to go through all the templates in an array to load enemies from them. I know that I could do this manually, but every time I will create a new type of enemy I would need to add it manually to the code (thus probably forgetting more than once).
My two options were:
1- Use a generic, and the above problem ensues.
2- Use a non-generic, and store the type inside, which would anchor the return type Generate() function. This would mean the generate function would output an array of objects, array which would need to be converted to the suitable type every single time a template generates an array of enemies.
I have a space in my head that tells me there is an elegant solution to all this, and I hope it is right!
Yes, C# 4 supports generic variants - but only in the declarations of interfaces and delegates, so you won't be able to do it in this case. Of course you could potentially create an interface:
public interface IGeneric<out T>
and then implement that in your classes, at which point you could create an IGeneric<Animal>.
If you can give more details about what you're trying to achieve, we may be able to help you find an alternative approach.
Jon Skeet's info aside, you might be able to do something like this:
public MyGeneric<T2> ToOtherType<T2>()
{
if (typeof(T2).IsAssignableFrom(typeof(T)))
{
// todo: get the object
return null;
}
else
throw new ArgumentException();
}
new MyGeneric<Dog>().ToOtherType<Animal>(),
new MyInheritedGeneric<Cat>().ToOtherType<Animal>()
If an array is going to hold more than one type of item, the items are going to have to be stored in heap objects which are separate from the array itself (if some of the types are structs, they'll have to either be boxed or stored as a field in a generic type which derives from a non-generic one). In most cases, the simplest thing to do will be to identify a common ancestor type for everything you'll be storing in the array, and simply typecast array elements as needed. There are a few cases where that won't be feasible, however. If, for example, your collection is going to hold objects whose type is unknown but is constrained to more than one interface, it will be necessary to pass those objects to generic routines whose method type parameter is similarly constrained, and the types that may be passed to your routine have no common ancestor which satisfies all constraints, there won't be any single type to which all members of your collection can be cast that would allow them to be passed as a suitable generic.
If the objects in your collection will only be passed to a small number of routines, it may be possible to have the generic method which adds items construct delegates to suitably invoke all the necessary routines and store those delegates as part of the collection. Lambda expressions or anonymous delegates may be convenient for this.
For example, suppose one will need to be able to feed items that are stored in a list to the Wibble<T> method of various IWibbler objects and the Wobble<T> method of various IWobbler objects, where the T types have interface constraints I1 and I2.
interface IWibbler { void Wibble<T>(T param, int param) where T : I1,I2; }
interface IWobbler { void Wobble<T>(T param, string param) where T: I1,I2; }
private struct WibbleWobbleDelegateSet
{
public Action<IWibbler, int> Wibble;
public Action<IWobbler, string> Wobble;
static WibbleWobbleDelegateSet Create<T>(T param) where T: I1, I2
{
var ret = new WibbleWobbleDelegateSet ();
ret.Wibble = (IWibbler wibbler, int p2) => { wibbler.Wibble<T>(param, p2); };
ret.Wobble = (IWobbler wobbler, string p2) => { wobbler.Wobble<T>(param, p2); };
return ret;
}
}
Calling WibbleWobbleDelegateSet.Create<T>(T param), with a suitably-constrained param, will yield a non-generic structure which contains delegates that can be used to pass the parameter supplied at struct creation to any IWibbler.Wibble<T>() or IWobbler.Wobble<T>() method.
This approach is only directly usable if the list of routines that will be called is known. If one needs to be able to call arbitrary routines with constrained generic parameters, it's possible to do that either with some tricky interfaces or with Reflection, but such things get more complicated.
I have a little problem for you guys.
I would like to do this:
Type[] classes = new Type[]{ Class1, Class2 };
foreach(Type t in classes){
List<t> list = new List<t>();
}
Is there some way to do this?
You cannot cast to a generic type at runtime, because the type in the generic needs to be resolved at compile time.
You can create a generic type in a dynamic manner using reflection, but unless you hard-code the cast, all you get in return is an object.
I cannot really tell what it is you want, I have to agree with a comment this is an XY problem. I would be inclined to make the presumptuous statement that there is a design issue somewhere that this is trying to solve, instead of addressing the design issue directly, or asking the question of what you are trying to achieve directly.
You can use the following code to create the type, then the dynamic type can be used to duck type the various members of List<T> without knowing/caring that it is a list or what T is:
using System;
using System.Collections.Generic;
namespace ConsoleApplication61
{
class Program
{
static void Main(string[] args)
{
dynamic o = CreateGeneric(typeof(List<>), typeof(int));
o.Add(1);
Console.WriteLine(o[0]);
Console.Read();
}
public static object CreateGeneric(Type generic, Type innerType, params object[] args)
{
System.Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
return Activator.CreateInstance(specificType, args);
}
}
}
The above sample duck types the Add method and the Indexer. The DLR does the type handling and the duck typing at runtime - knowing that 1 is an int, for example.
Just to clarify, I likely wouldn't use such code in production (unless you requirements are very specific to need this) and any issues with type-mismatching will occur at run time; so you either need to type very accurately (limited IntelliSense) or have good error handling.
Thanks to this blog post for the CreateGeneric method.
This assumes .NET 4 with the new CLR. As #MartinLiversage has also pointed out, this particular sample assumes that you are utilising the list in a sort-of-strongly-typed manner. In my example I am passing an int to a List<int> hidden in a dynamic.
We have been on .NET 4 almost since it was released. We have a large application with an even larger code base. dynamic isn't used once in the application, and only a few times in the test code base. That isn't to say "don't use it", it's to say "most of the time, you don't need it".
You can do it like this:
foreach(Type t in classes)
{
var listType = typeof(List<>).MakeGenericType(t);
var instance = Activator.CreateInstance(listType);
}
This is possible with the Type.MakeGenericType Method
Here's a nifty method I found that should work for ya: CodeRef
public static object CreateGeneric(Type generic, Type innerType, params object[] args)
{
System.Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
return Activator.CreateInstance(specificType, args);
}
And use it like so:
var o = CreateGeneric(typeof(List<>), t);
Unfortunately, to add items you'll have to do it like so (where item is the item you're adding).
MethodInfo addMethod = o.GetType().GetMethod("Add");
addMethod.Invoke(o, new object[] { item.ToType(t) });
Or use the Generic type as mentioned in another answer.
You can try this:
Type[] classes = new Type[] { typeof(A), typeof(B) };
foreach (Type t in classes)
{
Type genericType = typeof(List<>).MakeGenericType(t);
var list = Activator.CreateInstance(genericType);
}
If you want to keep to objects in one list then probably they have something in common.
In such case, I would argue that, just like L.B mentioned in a comment, you are asking a wrong question here.
Probably it's a design issuethat you have. Think about those types, see what they have in common and think about deriving from one base type or make both implement the same interface. In such case you would be able to instantiate a list of the objects of the base type/interface and work with those.
Just to give you a head start:
abstract class Vehicle {
public int NumberOfWheels { get; set; }
}
class Car : Vehicle
{
public Car()
{
NumberOfWheels = 4;
}
}
class Bicycle : Vehicle
{
public Bicycle()
{
NumberOfWheels = 2;
}
}
static void Main(string[] args)
{
var v1 = new Car();
var v2 = new Bicycle();
var list = new List<Vehicle>();
list.Add(v1);
list.Add(v2);
foreach (var v in list)
{
Console.WriteLine(v.NumberOfWheels);
}
Console.ReadKey();
}
I have a class:
class abc <T> {
private T foo;
public string a {
set {
foo = T.parse(value);
}
get{
return foo.toString();
}
}
}
However the T.parse command is giving me an error. Anyone of a way to do what I am trying to do?
I am using this as a base class for some other derived classes.
Edit:
What I ended us doing:
Delegate parse = Delegate.CreateDelegate(typeof(Func<String, T>), typeof(T).GetMethod("Parse", new[] { typeof(string) }));
I do that once in the constructor
and then I do the following in my property:
lock (lockVariable)
{
m_result = (T)parse.DynamicInvoke(value);
dirty = true;
}
C# generic types are not C++ templates. A template lets you do a fancy "search and replace" where you would substitute the name of a type that implements a static parse method for T. C# generics are not a textual search-and-replace mechanism like that. Rather, they describe parameterized polymorphism on types. With a template, all that is required is that the specific arguments you substitute for the parameters are all good. With a generic every possible substitution whether you actually do it or not, has got to be good.
UPDATE:
A commenter asks:
What would be the C# way of doing things when an equivalent to Haskell's Read type class is needed?
Now we come to the deep question underlying the original question.
To clarify for the reader unfamiliar with Haskell: Since C# 2.0, C# has supported "generic" types, which are a "higher" kind of type than regular types. You can say List<int> and a new type is made for you that follows the List<T> pattern, but it is a list specifically of integers.
Haskell supports an even higher kind of type in its type system. With generic types you can say "every MyCollection<T> has a method GetValue that takes an int and returns a T, for any T you care to name". With generic types you can put constraints on T and say "and furthermore, T is guaranteed to implement IComparable<T>..." With Haskell typeclasses you can go even further and say the moral equivalent of "...and moreover, T is guaranteed to have a static method Parse that takes a string and returns a T".
The "Read" typeclass is specifically that typeclass that declares the moral equivalent of "a class C that obeys the Read typeclass pattern is one that has a method Parse that takes a string and returns a C".
C# does not support that kind of higher type. If it did then we could typecheck patterns in the language itself such as monads, which today can only be typechecked by baking them into the compiler (in the form of query comprehensions, for example.) (See Why there is no something like IMonad<T> in upcoming .NET 4.0 for some more thoughts.)
Since there is no way to represent that idea in the type system, you're pretty much stuck with not using generics to solve this problem. The type system simply doesn't support that level of genericity.
People sometimes do horrid things like:
static T Read<T>(string s)
{
if (typeof(T) == typeof(int)) return (T)(object)int.Parse(s);
if ...
but that is in my opinion a bit abusive; it really is not generic.
You could use reflection. You cannot access static members through a generic parameter.
class Abc<T> {
private T foo;
public string a {
set {
foo = Parse<T>(value);
}
get {
return foo.ToString();
}
}
static T Parse<T>(string s)
{
var type = typeof(T);
var method = type.GetMethod("Parse", new[] { typeof(string) });
return (T)method.Invoke(null, new[] { s });
}
}
C# doesn't have templates. .NET generics don't work like C++ templates.
With an appropriate constraint, you can use instance methods on parameters with generic type, but there's no way to constrain static members.
However, you could use reflection, something along the lines of typeof(T).GetMethod("Parse"), to make a Func<string,T> delegate.
T.parse is not known in the generic parameter. You have to make it known.
dont use reflection. Its slow and generally a bad solution in this case.
use generics in a correct way.
You have to specify that T can be only classes which implement an interface which contains a parse method:
class abs<T> where T : IParsable<T>
{
//your implementation here
}
interface IParsable<T>
{
T Parse(string value);
}
public class Specific : IParsable<Specific>
{
public Specific Parse(string value)
{
throw new NotImplementedException();
}
}
You can't call a static method on a generic class.
Look at this post: Calling a static method on a generic type parameter
But here is a little workaround:
public interface iExample
{
iExample Parse(string value);
}
class abc<T> where T : iExample, new()
{
private T foo;
public string a
{
set
{
foo = (T)(new T().Parse(value));
}
get
{
return foo.ToString();
}
}
}
So if you have an class that implements iExample
public class SelfParser : iExample
{
public iExample Parse(string value)
{
return new SelfParser();
}
}
You will be able to use it like this:
abc<SelfParser> abcInstance = new abc<SelfParser>();
abcInstance.a = "useless text";
string unParsed = abcInstance.a; // Will return "SelfParser"
While you can't do exactly that with Generics (there are no type constraints for that enforce a specific method signature, only struct/object/interface constraints).
You can create a base class whose constructor takes the Parse method. See my Int32 implementation at the bottom.
class MyParseBase <T>
{
public MyBase (Func<string,T> parseMethod)
{
if (parseMethod == null)
throw new ArgumentNullException("parseMethod");
m_parseMethod = parseMethod;
}
private T foo;
public string a {
set
{
foo = m_parseMethod(value);
}
get
{
return foo.toString();
}
}
}
class IntParse : MyParseBase<Int32>
{
public IntParse()
: base (Int32.Parse)
{}
}
This is a variation on Oleg G's answer which removes the need for the new() type constraint. The idea is you make a Parser for each type you want to be contained in an abs, and inject it - this is a formalization of the Func<string, T> approach as well.
interface IParser<T>
{
T Parse(string value);
}
class abs<T>
{
private readonly IParser<T> _parser;
private T foo;
public abs(IParser<T> parser)
{
_parser = parser;
}
public string a {
set
{
foo = _parser.Parse(value);
}
get
{
return foo.ToString();
}
}
class abc<T> {
private T foo;
public string a {
set {
var x_type = typeof(T);
foo = (T)x_type.InvokeMember("Parse", System.Reflection.BindingFlags.InvokeMethod, null, value, new []{value});
}
get{
return foo.ToString();
}
}
}
I was hoping to do something like this, but it appears to be illegal in C#:
public Collection MethodThatFetchesSomething<T>()
where T : SomeBaseClass
{
return T.StaticMethodOnSomeBaseClassThatReturnsCollection();
}
I get a compile-time error:
'T' is a 'type parameter', which is not valid in the given context.
Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.
In this case you should just call the static method on the constrainted type directly. C# (and the CLR) do not support virtual static methods. So:
T.StaticMethodOnSomeBaseClassThatReturnsCollection
...can be no different than:
SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection
Going through the generic type parameter is an unneeded indirection and hence not supported.
To elaborate on a previous answer, I think reflection is closer to what you want here. I could give 1001 reasons why you should or should not do something, I'll just answer your question as asked. I think you should call the GetMethod method on the type of the generic parameter and go from there. For example, for a function:
public void doSomething<T>() where T : someParent
{
List<T> items=(List<T>)typeof(T).GetMethod("fetchAll").Invoke(null,new object[]{});
//do something with items
}
Where T is any class that has the static method fetchAll().
Yes, I'm aware this is horrifically slow and may crash if someParent doesn't force all of its child classes to implement fetchAll but it answers the question as asked.
You can do what I call a surrogate singleton, I've been using it as a sort of "static inheritance" for a while
interface IFoo<T> where T : IFoo<T>, new()
{
ICollection<T> ReturnsCollection();
}
static class Foo<T> where T : IFoo<T>, new()
{
private static readonly T value = new();
public static ICollection<T> ReturnsCollection() => value.ReturnsCollection();
}
// Use case
public ICollection<T> DoSomething<T>() where T : IFoo<T>, new()
{
return Foo<T>.ReturnsCollection();
}
The only way of calling such a method would be via reflection, However, it sounds like it might be possible to wrap that functionality in an interface and use an instance-based IoC / factory / etc pattern.
It sounds like you're trying to use generics to work around the fact that there are no "virtual static methods" in C#.
Unfortunately, that's not gonna work.
I just wanted to throw it out there that sometimes delegates solve these problems, depending on context.
If you need to call the static method as some kind of a factory or initialization method, then you could declare a delegate and pass the static method to the relevant generic factory or whatever it is that needs this "generic class with this static method".
For example:
class Factory<TProduct> where TProduct : new()
{
public delegate void ProductInitializationMethod(TProduct newProduct);
private ProductInitializationMethod m_ProductInitializationMethod;
public Factory(ProductInitializationMethod p_ProductInitializationMethod)
{
m_ProductInitializationMethod = p_ProductInitializationMethod;
}
public TProduct CreateProduct()
{
var prod = new TProduct();
m_ProductInitializationMethod(prod);
return prod;
}
}
class ProductA
{
public static void InitializeProduct(ProductA newProduct)
{
// .. Do something with a new ProductA
}
}
class ProductB
{
public static void InitializeProduct(ProductB newProduct)
{
// .. Do something with a new ProductA
}
}
class GenericAndDelegateTest
{
public static void Main()
{
var factoryA = new Factory<ProductA>(ProductA.InitializeProduct);
var factoryB = new Factory<ProductB>(ProductB.InitializeProduct);
ProductA prodA = factoryA.CreateProduct();
ProductB prodB = factoryB.CreateProduct();
}
}
Unfortunately you can't enforce that the class has the right method, but you can at least compile-time-enforce that the resulting factory method has everything it expects (i.e an initialization method with exactly the right signature). This is better than a run time reflection exception.
This approach also has some benefits, i.e you can reuse init methods, have them be instance methods, etc.
You should be able to do this using reflection, as is described here
Due to link being dead, I found the relevant details in the wayback machine:
Assume you have a class with a static generic method:
class ClassWithGenericStaticMethod
{
public static void PrintName<T>(string prefix) where T : class
{
Console.WriteLine(prefix + " " + typeof(T).FullName);
}
}
How can you invoke this method using relection?
It turns out to be very easy… This is how you Invoke a Static Generic
Method using Reflection:
// Grabbing the type that has the static generic method
Type typeofClassWithGenericStaticMethod = typeof(ClassWithGenericStaticMethod);
// Grabbing the specific static method
MethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod("PrintName", System.Reflection.BindingFlags.Static | BindingFlags.Public);
// Binding the method info to generic arguments
Type[] genericArguments = new Type[] { typeof(Program) };
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);
// Simply invoking the method and passing parameters
// The null parameter is the object to call the method from. Since the method is
// static, pass null.
object returnValue = genericMethodInfo.Invoke(null, new object[] { "hello" });
As of now, you can't. You need a way of telling the compiler that T has that method, and presently, there's no way to do that. (Many are pushing Microsoft to expand what can be specified in a generic constraint, so maybe this will be possible in the future).
Here, i post an example that work, it's a workaround
public interface eInterface {
void MethodOnSomeBaseClassThatReturnsCollection();
}
public T:SomeBaseClass, eInterface {
public void MethodOnSomeBaseClassThatReturnsCollection()
{ StaticMethodOnSomeBaseClassThatReturnsCollection() }
}
public Collection MethodThatFetchesSomething<T>() where T : SomeBaseClass, eInterface
{
return ((eInterface)(new T()).StaticMethodOnSomeBaseClassThatReturnsCollection();
}