Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curiously Recurring Template Pattern and generics constraints (C#)

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?

like image 481
Paolo Tedesco Avatar asked Aug 25 '09 11:08

Paolo Tedesco


Video Answer


1 Answers

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 { ... }
like image 153
mmx Avatar answered Oct 01 '22 02:10

mmx