Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Generic Objects in C#

I have a simple class that includes 2 properties, one String and one a List of generic Objects. It looks like this:

public class SessionFieldViewModel
{
    private String _name;
    public String Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private List<Object> _value;
    public List<Object> Value
    {
        get { return _value ?? new List<Object>(); }
        set { _value = value; }
    }
}

Within my main code (MVC Controller) I am trying to manually populate this class. Keep in mind that when I pass data from a webform into this class using the default model binder this get populated just fine.

When Manually trying to create a record and and add it to a list I do this:

        Guid id = Guid.NewGuid();

        var _searchField = new SessionFieldViewModel();
        _searchField.Name = "IDGUID";
        Object _object = (Object)id;
        _searchField.Value.Add(_object);

        _searchFields.Fields.Add(_searchField);

When I do this I do get a populated class with a Name property of "IDGUID", but the generic lists of objects comes back null.

When I debug the code and walk it though the data seems to all be there and working as I am doing it, but when I get through and inspect _searchFields it does not show anything in the Value property of Fields.

Ideas?

Thanks in advance.

Tom tlatourelle

like image 501
tlatourelle Avatar asked Feb 01 '26 20:02

tlatourelle


2 Answers

It appears you never set _value when it is null from the getter. Try

public List<Object> Value
{
    get { return _value ?? (_value = new List<Object>()); }
    set { _value = value; }
}
like image 191
Ed Chapel Avatar answered Feb 04 '26 12:02

Ed Chapel


_value is never getting set to an instance of List<Object>; it is always null. What's happening is you are returning a new List<Object> and adding an Object to it, but you're immediately discarding the newly-created List<Object>.

You need to change your definition of Value to something like this:

private List<Object> _value = new List<Object>();
public List<Object> Value
{
    get { return _value; }
    set { _value = value; }
}
like image 32
Jon Sagara Avatar answered Feb 04 '26 11:02

Jon Sagara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!