jeudi 19 septembre 2019

Why can't c# infer casting?

So i recently started working with reflection for the first time, and found GetType() to know the original type of an object, even if it is just stored as an object.

foreach(object o in (IEnumerable) property.GetValue(element))
{
    List(o, verbose, int.MaxValue, subIncludes[attribute.Name], indents + 4);
}

So here o is actually getting passed into a generic method. I found that after getting passed in, o.GetType(); returns the actual class type and not System.Object which surprised me. For arguments sake lets say the type is Product. So if the type is already known, why is it necessary to cast o to Product like so Product p = (Product) o;instead of just doing Product p = o? Why not infer that casting is the desired outcome since the type is already known?





Aucun commentaire:

Enregistrer un commentaire