To pass anonymous types around, consider using dynamic. A longer example is shown below and the technique you can use. For example, consider calling the TreadSafeDynamicObject here 'CustomEmployee' to make more sense of the code. The code has a constructor that accepts a dynamic object (your anonymous, potentially nested class), for example :
var someCustomEmploye = new {
IsIntern = false,
EmployeeFacts = new {
IsSenior = true,
BirthDate = new DateTime(1960, 1, 1)
}
};
You can transform someCustomEmployee to a dynamic object using the technique shown below, for example pass in 'someCustomEmployee' into the constructor, in my code it would be:
dynamic someEmp = new ThreadSafeDynamicObject(someCustomEmployee);
Once you have transformed someEmp into a proper dynamic object, your LogEmployee function can for example serialize the object and log it or handle it in some other way (note that you do not have to go via converting it to a dynamic object anyways, if it is enough to just serialize the anonymous class instance).
Example :
dynamic threadSafeToyota = new ThreadSafeDynamicObject(new {
Make = "Toyota",
Model = "CR-H",
Propulsion = new {
IsHybrid = true,
UsesPetrol = true,
ElectricMotor = true
}
});
The code accepts a dynamic object and uses a private method 'ToDictionary' to convert the object graph of the anonymous class instance provided as an alternative way to set properties on the dynamic object.
Note that I also have added some more code here to provide thread safety when setting and getting properties.
public class ThreadSafeDynamicObject : DynamicObject, IEnumerable<KeyValuePair<string, object>>
{
public ThreadSafeDynamicObject()
{
}
public ThreadSafeDynamicObject(dynamic members)
{
var membersDict = ToDictionary(members);
InitMembers(membersDict);
}
private IDictionary<string, object> ToDictionary(object data)
{
var attr = BindingFlags.Public | BindingFlags.Instance;
var dict = new Dictionary<string, object>();
foreach (var property in data.GetType().GetProperties(attr))
{
if (property.CanRead)
{
dict.Add(property.Name, property.GetValue(data, null));
}
}
return dict;
}
private void InitMembers(IDictionary<string, object> membersDict)
{
foreach (KeyValuePair<string, object> member in membersDict){
_members.AddOrUpdate(member.Key, member.Value, (key, oldValue) => member.Value);
}
}
private readonly ConcurrentDictionary<string, object> _members = new();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members.AddOrUpdate(binder.Name, value, (key, oldvalue) => value);
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys.ToList().AsReadOnly();
}
public override string ToString()
{
return JsonSerializer.Serialize(_members);
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _members.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _members.GetEnumerator();
}
}
When running the code inside Linqpad 7 I got this output (I am using static System.Console and using System.Dynamic here):
WriteLine(threadSafe.ToString());
WriteLine(threadSafe.Make);
WriteLine(threadSafe.Model);
WriteLine(threadSafe.Propulsion.IsHybrid);
WriteLine(threadSafe.Propulsion.UsesPetrol);
WriteLine(threadSafe.Propulsion.ElectricMotor);
There are several advantages to this. It supports nested levels as you can see in the output and is very flexible. The method 'ToDictionary' is essential here. Also, we do not have to use additional libraries outside the .net framework, so the funtionality is built in. I have not checked all variants of this code, at least it supports the typical scenarios of anonymous type object graphs.
Key thing here is to transform your anonymous type first into a dictionary and then populate the internal concurrent dictionary with the members ('fields' or 'props') of the derived DynamicObject.
There are several ways to solve this :
You could do boxing. E.g. have a method that accepts object and use reflection to extract the properties and log the properties and their values
E.g. :
public void LogEmployees(object someCustomEmployee) { // .. }
You could transform the anonymous object into a dynamic object as shown in my sample
In addition to boxing or converting into a dynamic object, you could avoid reflection by serializing the converted object (either boxed object or dynamic variant).