In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type. A generic class, such as GenericList
listed in Introduction to Generics, cannot be used as-is because it is not really a type; it is more like a blueprint for a type.
In my case I wanted to have two different generic list names, generated from different classes, but those classes would be inherited from one class, something like this:
class IDName
{
public Guid ID;
public string Name;
}
class FirstIDName: IDName { }
class SecondIDName : IDName { }
Then I need one method to fill those classes:
public static void AddToIDName<T>(List<T> iDNameList, string name) where T : IDName, new()
{
iDNameList.Add(new T
{
ID = Guid.NewGuid(),
Name = name
});
}
Here notice constraint "where T : IDName, new()". I needed constraint new because of line: "iDNameList.Add(new T"
Whole example:
using System;
using System.Collections.Generic;
namespace GenericList
{
class Program
{
static void Main(string[] args)
{
List<FirstIDName> firstIDNames = new List<FirstIDName>();
List<SecondIDName> secondIDNames = new List<SecondIDName>();
AddToIDName(firstIDNames, "firstIDNameTestOne");
AddToIDName(firstIDNames, "firstIDNameTestTwo");
AddToIDName(secondIDNames, "secondIDNameTestOne");
AddToIDName(secondIDNames, "secondIDNameTestTwo");
AddToIDName(secondIDNames, "secondIDNameTestThree");
Console.WriteLine("FirstIDName");
foreach (FirstIDName firstIDName in firstIDNames)
{
Console.WriteLine($"id: {firstIDName.ID}, name: {firstIDName.Name}");
}
Console.WriteLine("SecondIDName");
foreach (SecondIDName secondIDName in secondIDNames)
{
Console.WriteLine($"id: {secondIDName.ID}, name: {secondIDName.Name}");
}
Console.WriteLine("");
Console.WriteLine("The end");
Console.ReadKey();
}
public static void AddToIDName<T>(List<T> iDNameList, string name) where T : IDName, new()
{
iDNameList.Add(new T
{
ID = Guid.NewGuid(),
Name = name
});
}
}
}