Can anyone explain me this issue?
the only way to get this working, is to use the virtual in the CorrectName and then override in the Derived one, instead of new keyword, but, WHY is this happening?
WHY if I cast by generic it gives me the Base value, and if I cast it directly it gives me Derived value? ((Output is below))
Thanks guys, as I've said you, I already got the "solution", but I want to UNDERSTAND
class Base
{
public string Name { get; set; }
public string CorrectName { get { return Name; } }
}
class Derived : Base
{
public new string CorrectName { get { return "NEW" + Name; } }
}
static void Main(string[] args)
{
List<Derived> container = new List<Derived>();
var d = new Derived() { Name = "NameDerived2" };
container.Add(d);
Search<Derived>(container);
Console.ReadLine();
}
static void Search<T>(List<T> list) where T : Base
{
foreach (var el in list)
{
Console.WriteLine("No Cast -->" + el.CorrectName);
Console.WriteLine("Generic Cast -->" + (el as T).CorrectName);
Console.WriteLine("Direct Cast -->" + (el as Derived).CorrectName);
}
}
OUTPUT:
No Cast -->NameDerived2
Generic Cast -->NameDerived2
Direct Cast -->NEWNameDerived2
TABLE OF TRUTH:
el is Derived == true
el.GetType().Equals(typeof(Derived)) == true
el.GetType().Equals(typeof(T)) == true
el.GetType().Equals(typeof(Base)) == false
typeof(T).Equals(typeof(Base)) == false
typeof(T).Equals(typeof(Derived)) == true