Elad Lachmi
Elad Lachmi

Reputation: 10581

Access properties of a type created by reflection

I have the following code:

List<MultiServiceRequestMember> _memberList = new List<MultiServiceRequestMember>();
var type = Type.GetType(svc.NotificationClassName); <- this is a string of the class name.
MultiServiceRequestMember newMember = (MultiServiceRequestMember)Activator.CreateInstance(type);

_memberList.add(newMember);

The MultServiceRequestMember is a base type and I want to assign values to properties specific to type. My question is: How do I cast newMember to type and access its properties?

Upvotes: 0

Views: 90

Answers (2)

empi
empi

Reputation: 15901

You will have to change the code to look like this:

List<MultiServiceRequestMember> _memberList = new List<MultiServiceRequestMember>();
var type = Type.GetType(svc.NotificationClassName);
MultiServiceRequestMember newMember = null;
if (type == typeof(MultiServiceRequestMemberA))
{
    newMember = new MultiServiceRequestMemberA();
    //set specific properties
}
else if (type == typeof(MultiServiceRequestMemberB)) //etc.
{
    //...
}
else
{
    //throw or some default
}

_memberList.add(newMember);

However, it looks like code smell. I guess you're trying to initialize an object based on some other object (let's call it NotificationInfo). Then instead of code that looks like this:

if (type == typeof(MultiServiceRequestMemberA))
{
    newMember = new MultiServiceRequestMemberA();
    newMember.A = notificationInfo.A;
}

Maybe should think of following design:

class MultiServiceRequestMember
{
    public virtual void Initialize(NotificationInfo notificationInfo) //or abstract if you wish
    {
    }
}

class MultiServiceRequestMemberA : MultiServiceRequestMember
{
    public override void Initialize(NotificationInfo notificationInfo)
    {
        base.Initialize(notificationInfo);
        this.A = notificationInfo.A;
    }
}

And then you will be able to leave your previous code and just call Initialize.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503260

How do I cast newMember to type and access it's properties?

You can't cast it, because you don't know the specific type at compile-time. If you did, you wouldn't need reflection in the first place!

You'll have to set the properties by reflection too:

// TODO: Checking that you managed to get the property, that's it's writable etc.
var property = type.GetProperty("PropertyName");
property.SetValue(newMember, "new value", null);

Upvotes: 3

Related Questions