Search code examples
c#asp.netasp.net-mvcienumerableidictionary

c# asp mvc how to get derived class object values


Can anyone help how to get derived class objects values?

When I try to cast from derived class (Currency) to parent class (Entity) I get null's. Real values from DB: http://prntscr.com/ahmy9h Null's after casting to Entity: http://prntscr.com/ahmxxo

public class Entity
{
    public System.Guid Id { get; set; }
    public string Name { get; set; }
}

public class Currency:Entity
{
    public Currency()
    {
        this.BankServices = new HashSet<BankService>();
    }

    public new System.Guid Id { get; set; }
    public new string Name { get; set; }

    public virtual ICollection<BankService> BankServices { get; set; }
}

public virtual IEnumerable<Entity> GetItems()
{
    // check the cache
    Dictionary<Guid, Entity> EntityData = GetCachedData();

    // If it's not in the cache, read it from the repository
    if (EntityData == null)
    {
        // Get the data
        Dictionary<Guid, Entity> EntityDataToCache = new Dictionary<Guid, Entity>();

        // get data from the repository
        IEnumerable<Entity> entityDataFromDb = LoadData();
        foreach (var item in entityDataFromDb)
        {
            var itemValue = item; // ALL ZEROS http://prntscr.com/ahmxxo
            var itemValue2 = (Currency)item; // REAL VALUES http://prntscr.com/ahmy9h
            EntityDataToCache[(Guid)item.GetType().GetProperty("Id").GetValue(item, null)] = item;
        }

        if (EntityDataToCache.Any())
        {
            // Put this data into the cache for 30 minutes
            Cache.Set(CacheKey, EntityDataToCache, 30);
        }
    }

    var cache = Cache.Get(CacheKey);

    var result = cache as Dictionary<Guid, Entity>;
    return result.Values;
}

Solution

  • I would suggest reading this or something similar to brush up on the difference between inheritance and hiding. In your case, the new modifier on the Currency.Id and Currency.Name properties tells the compiler to hide those properties in the parent class. So, when you assign those properties in a Currency instance, those values are only applicable to that instance as an instance of Currency. As you've seen from your code, if you cast that instance to an instance of Entity, references to those properties are references to the Entity properties (which you haven't set). In order to get the behavior I think you're looking for, you'll want to add the virtual modifier to the property declarations in Entity, then change new to override in Currency. Of course, if you're not changing the behavior of these properties between Currency and Entity then you don't need to override them in Currency at all...they'll be available to all classes that inherit from Entity. Hope that helps.