What i really want is to understand is why when using an interface as a constraint on a generic class I am able to access the "Nume" property that I defined in a class that implements that interface. My questions are:
- Why do I have to add the interface as a constraint in the generic class while I already implemented it in the initial Tr class?
- Why I cannot access the property directly from the class and why I am able to access it by implementing the interface?
Without the interface I cannot access the property from the Tr class, so I implemented the solution found on this Stackoverflow question,it seems to work but i cannot understand exactly why.
I also looked on this Microsoft documentation.
interface GET
{
int Nume { get; }
}
class Tr : GET
{
public int Nume { get; }
public Tr() { }
public Tr(int num)
{
this.Nume = num;
}
}
class Program<Tr> where Tr : GET
{
static List<Tr> lst = new List<Tr>();
public void Test(Tr merge)
{
lst.Add(merge);
foreach (Tr cadt in lst)
{
Console.WriteLine($"Numarul este {cadt.Nume}");
}
}
}
class MainC
{
static void Main(string[] args)
{
Tr cc = new Tr(2);
Program<Tr> cls = new Program<Tr>();
cls.Test(cc);
}
}
I expected This code to work without the help of an interface, but it crashed. It works with the help of the interface.