How to Define that a Type T must have a field "ID"

.net, c#, generics

Solution

You could create an interface:

public interface IWithID
{
    // For your method the set(ter) isn't necessary
    // public int ID { get; set; } 
    public int ID { get; }
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
        where T: IWithID

You'll need to use a property, not a field in this way.

Or clearly you could use a base type...

public abstract class WithID
{
    // public int ID; // non readonly
    public readonly int ID; // can even be a field
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
        where T: WithID

Another solution is to pass a delegate:

public static void createDictionary<T>(IEnumerable<T> myRecords, 
                                       Func<T, int> getID)

then you use the `GetID` to get the ID, like `myRecords.ToDictionary(getID)`

Problem

This sample: ``` public static void createDictionary<T>(IEnumerable<T> myRecords) where T: T.ID // Wont Compile { IDictionary<int, T> dicionario = myRecords.ToDictionary(r => r.ID); foreach (var item in dicionario) { Console.WriteLine("Key = {0}",item.Key); Type thisType = item.Value.GetType(); StringBuilder sb = new StringBuilder(); foreach (var itemField in thisType.GetProperties()) { sb.AppendLine(string.Format("{0} = {1}", itemField.Name, itemField.GetValue(item.Value, null))); } Console.WriteLine(sb); } } ``` how can I force the type passed as parameter has a field called "ID"?

Original source