Continuting from the previous
post, here is an example that answer Ian's second question
"...Also I am not sure I understand what you mean towards the end when
you talk about
constraining a generic type to a class or its superclass. How would this be useful?
You would
not be able to use any subclass-specific behaviour without resorting to type checking
(similar to covariance not allowed for parameters of overriding methods)."
using System;
using System.Collections.Generic;
using System.Text;
namespace ConstraintsExample
{
class MyList<T>
{
public void CopyTo(MyList<T>
list2)
{//...
}
}
class Animal
{
public void Play<T>(List<T>
animals) where T : Animal
{ }
}
class Dog
: Animal { }
class Program
{
public static void CopyList<T1,
T2>(List<T1> animals1, List<T2> animals2)
where
T1 : T2
//
Work around to get this working.
{ //...
}
static void Main(string[]
args)
{
Dog aDog = new Dog();
aDog.Play(new List<Animal>());
aDog.Play(new List<Dog>());
//
The constraint in play is needed for above
List<Animal> animalsList1a = new List<Animal>();
List<Animal> animalsList2a = new List<Animal>();
List<Dog> dogsList1a = new List<Dog>();
List<Dog> dogsList2a = new List<Dog>();
CopyList(animalsList1a, animalsList2a);
CopyList(dogsList1a, dogsList2a);
CopyList(dogsList1a, animalsList1a); //
How do you allow this?
//
We got around by using the constraint in Copy as you can see
MyList<Animal> animalsList1b = new MyList<Animal>();
MyList<Animal> animalsList2b = new MyList<Animal>();
MyList<Dog> dogsList1b = new MyList<Dog>();
MyList<Dog> dogsList2b = new MyList<Dog>();
animalsList1b.CopyTo(animalsList2b);
dogsList1b.CopyTo(dogsList2b);
dogsList1b.CopyTo(animalsList1b); //
ERROR
//
How do you allow above without allowing the following
//dogsList1b.CopyTo(new
MyList<Program>());
//The
workaround used in CopyList does not work here:
//
In class MyList,
//
if I try
//
public void CopyTo<T2>(MyList<T2> list2) where T : T2
//
it gives an error that T is not being defined here.
//
Again, you can try to device some workarounds, but, like I mentioned on
//
the show, it would be *nice* to constrain that a parametric type is
//
a base of another parameteric type. I am wondering if Microsoft
//
has plans to support this in the future. My point is not "this is a big flaw."
//
Instead, "it would be a nice features to have" to make me 100% happy :)
}
}
}