I'm trying to understand generic constraints. Sadly I've got no reason to use them at the moment but trying my best to come up with situations so I can play with it and understand how/when they will help.
I've run into an issue. To me, these 2 are the same
public List<T> Get<T>() where T : DemoClassTwo
public List<DemoClassTwo> Get()
Both will return a List, and have to be of type DemoClassTwo and so I don't see why I'd use the method with that constraint.
Some actual code to demonstrate this
static void Main(string[] args)
{
var dco = new DemoClassOne();
dco.Get().ForEach((a) => { Console.WriteLine(a.Id); });
dco.Get<DemoClassTwo>().ForEach((a) => { Console.WriteLine(a.Id); });
Console.ReadKey();
}
And the supporting classes
public class DemoClassOne
{
public List<T> Get<T>() where T : DemoClassTwo, new()
{
var result = new List<T>();
var t = new T();
t.Id = 1;
result.Add(t);
return result;
}
public List<DemoClassTwo> Get()
{
var result = new List<DemoClassTwo>();
var d = new DemoClassTwo();
d.Id = 1;
result.Add(d);
return result; //Code here is pretty much identical to the other Get method
}
}
public class DemoClassTwo
{
public int Id { get; set; }
public DemoClassTwo()
{}
}
Have I just found a situation where the 2 are the same or am I missing something in the way it works.
This question is similar to In C#, why use Where T : ConcreteClass? but different as I'm not asking why to use it, but why it is different.