user1102550
user1102550

Reputation: 543

expression does not have a name error - dynamic C# object

I want to serialize a list of objects which could be of lots of different types which I've done in the function below. But I want to give a name to each object. I looked at using nameof but I get "expression does not have a name" when I do this - nameof(LogProperties[i]). Are there any ways to achieve this - I was thinking is there a way to add a metaproperty to the objects I want to log. I'm open to alternative suggestions.

    public static string CreateAdditionaLog(params object[] LogProperties)
    {
        var log = new ExpandoObject() as IDictionary<string, Object>;

        for (int i = 0; i < LogProperties.Length; i++)
        {
            var prop = LogProperties[i];
            log.Add(prop.GETNAME(), prop);
        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(log);
    }

Upvotes: 2

Views: 4175

Answers (1)

M B
M B

Reputation: 2326

If you are looking for the object name, you can use reflection to get the Type of the object

for (int i = 0; i < LogProperties.Length; i++)
        {
            var prop = LogProperties[i];
            log.Add(prop.GetType().Name, prop);
        }

Upvotes: 1

Related Questions