Search This Blog

Wednesday, May 13, 2015

C# Generic Interface Example

C# > Generics > Generic Interface 

Example


class Serializer1 { public string Name { get; set; } };
class Serializer2 { public string Name { get; set; } };

interface GenericSerializer<T>
{
      string Name(T tValue);
}

class Serializer<T>: GenericSerializer<T>
{
public string Name(T tValue)
        {
            var prop = tValue.GetType().GetProperty("Name");
            return prop.GetValue(tValue, null) as string;
        }
}

Serializer1 s1 = new Serializer1() { Name = "Serializer1" };
Serializer2 s2 = new Serializer2() { Name = "Serializer2" };

Serializer<Serializer1> serializer1 = new Serializer<Serializer1>();
string name1 = serializer1.Name(s1);

Serializer<Serializer2> serializer2 = new Serializer<Serializer2>();

string name2 = serializer2.Name(s2);