MadHenchbot
MadHenchbot

Reputation: 1385

trouble setting values to a collection in an abstract class

I'm working with reflection on an abstract class, and running into an issue where I'm unable to use the PropertyInfo.SetValue method to assign values to an existing List object.

Here are some (very) shortened class declarations.

public abstract class User { }
public class Subscriber : User
{
    public string Name { get; set; }
    public List<string> AttributeList { get; set; }
}

Now inside of User, I have a method that extracts data from an XML with an unknown number of elements. I parse through these elements, and if they are recognized as a property of User (or any of its children), I populate the property.

private void ExtractElement(XElement inner)
{
    // Uses reflection to get the correct Derived class (Initiate, Member, Subscriber)
    Type tUser = this.GetType();

    var prop = tUser.GetProperty("AttributeList"); // hard-coded for brevity
    object value = "Random Value" // same

    var nullableType = Nullable.GetUnderlyingType(prop.PropertyType);
    if (nullableType == null)
        nullableType = prop.PropertyType;


    if (nullableType == typeof(int))
    {
        prop.SetValue(this, int.Parse(value as string), null);
    }
    else if (nullableType == typeof(List<string>))
    {
        var myList = (List<string>)(prop.GetValue(this, null));
        myList.Add(value as string);
        prop.SetValue(this, myList, null); // <- This doesn't save changes.
    }
    else
    {
        prop.SetValue(this, value as string, null);
    }

When it drops into this last section, myList is populated correctly. But when I attempt to set the value of AttributeList to myList, the changes don't 'stick'. Judging from other posts about reflection, my best guess is that I am pulling a copy of AttributeList (because of boxing/unboxing?), and affecting that instead of the original. Is there a way to directly affect the original in this type of situation? Why doesn't the last line of my code throw an error if the changes aren't saved?

Upvotes: 2

Views: 128

Answers (1)

Mohammed Hossain
Mohammed Hossain

Reputation: 1319

As requested:

if (nullableType == typeof(List<string>))
{
    ((List<string>)(prop.GetValue(this, null))).Add(value as string);
}

Upvotes: 2

Related Questions