ProfK
ProfK

Reputation: 51064

How can I retrieve strongly typed properties from an anonymous type?

I'm using anonymous types to pass collections of typed objects to a TemplateResolver, where the named placeholders in a newly instantiated text template may source values from multiple objects, e.g.

var body = TemplateResolver.ResolveTemplate(template.ExternalRecipientBody, new {Sender = customer, NewJobCard = jobCard});

where the template has placeholders like {Sender$Surname} and {NewJobCard$JobNumber}.

Inside ResolveTemplate I need Sender and NewJobCard to be strongly typed, without knowing what to cast them to.

SOLUTION SO FAR

I have come up with this so far, but dislike having to use a string member name. I have asked another question on the possibility of somehow lmbda'ring the string out of at least the method call, even if not the method body.

    private T GetAnonymousTypeMember<T>(object anonymousType, string memberName) where T: class 
    {
        var anonTypesType = anonymousType.GetType();
        var propInfo = anonTypesType.GetProperty(memberName);
        return propInfo.GetValue(anonymousType, null) as T;
    }

Upvotes: 0

Views: 778

Answers (1)

RPM1984
RPM1984

Reputation: 73132

Anonymous types only have method scope, therefore you won't be able to access the strongly typed properties in the "ResolveTemplate" method.

You've got 2 choices:

  1. Box/unbox
  2. Bite the bullet and declare a struct/class

If you need "resolve" the properties from multiple sources, then consider using a form of OO abstraction (interface/abstract class) to pass the types around.

Upvotes: 1

Related Questions