I would like to create a method in a base generic class to return a specialized collection of derived objects and perform some operations on them, like in the following example:
using System;
using System.Collections.Generic;
namespace test {
class Base<T> {
public static List<T> DoSomething() {
List<T> objects = new List<T>();
// fill the list somehow...
foreach (T t in objects) {
if (t.DoSomeTest()) { // error !!!
// ...
}
}
return objects;
}
public virtual bool DoSomeTest() {
return true;
}
}
class Derived : Base<Derived> {
public override bool DoSomeTest() {
// return a random bool value
return (0 == new Random().Next() % 2);
}
}
class Program {
static void Main(string[] args) {
List<Derived> list = Derived.DoSomething();
}
}
}
My problem is that to do such a thing I would need to specify a constraint like
class Base<T> where T : Base {
}
Is it possible to specify a constraint like that somehow?
This might work for you:
class Base<T> where T : Base<T>
You can't constrain T
to an open generic type. If you need to constrain T
to Base<whatever>
, you'll need to construct something like:
abstract class Base { }
class Base<T> : Base where T : Base { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With