Asons
Asons

Reputation: 87191

Cast to custom object at runtime

Today I have several models/classes like these:

public class Event
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Reportage
{
    public string Author { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

These are each a part of several Razor pages, that has code that is more or less 100% same but a few lines, which are not, e.g. like this one, being unique on every page:

List<Event> itemList = Utility.GetCachedData<List<Event>>("event.json");

To get a more maintainable code, I decided to try to use as much generic code as possible, and the first issue I had were how to check if a given property existed, and if, assign that one of my defaults.

For that I found how-to using reflection, and did:

var pi = itemList[0].GetType().GetProperty("Date");
if (pi != null)
    pi.SetValue(itemList[0], DateTime.Now, null);

Next step were to do something similar e.g with List<Event> itemList;, and for that I found Convert.ChangeType(object, type), and did:

var itemList =  Convert.ChangeType(itemObj, typeof(List<Event>));

The problem with this one is, that I can't do this to get/set the Date

itemList[0].Date

Is there a way to solve that at runtime (other than with reflection), and use standard dot notation to get/set values?

Upvotes: 0

Views: 278

Answers (1)

mm8
mm8

Reputation: 169200

Is there a way to solve that at runtime (other than with reflection), and use standard dot notation to get/set values?

You can't use the dot notation to set a property Date of a type Event unless you actually cast the variable to a Event first:

var item =  (Event)Convert.ChangeType(itemObj, typeof(Event));
item.Date = ...;

Obviously this assumes that ChangeType actually returns an Event.

Please refer to the following blog post for more information.

Generic type parameters and dynamic types in C#

Upvotes: 2

Related Questions