Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data items to a List<Struct>

Tags:

c#

asp.net

I have the following struct defined in a user control:

public struct ColumnData
{
    public string ColumnName { get; set; }
    public string ColumnDataItem { get; set; }
    public bool ColumnIsHyperLink { get; set; }
    public string ColumnHyperLinkURL { get; set; }
    public string ColumnHyperLinkPK { get; set; }
}

I create a new instance of List<ColumnData> (In a different code behind that creates an instance of the user control) and want to pass in values to it, but how do I assign them to specific attributes within the struct object?

I create an instance of the struct using the following code:

List<ColumnData> DataItems = new List<ColumnData>();
like image 626
Theomax Avatar asked Sep 19 '11 11:09

Theomax


2 Answers

This:

List<ColumnData> DataItems = new List<ColumnData>();

creates a new list.

This:

List<ColumnData> DataItems = new List<ColumnData>();
var cd = new ColumnData();
cd.ColumnName = "Taco";
DataItems.Add(cd);

creates a new list, a new struct, and adds an item to the list.

like image 128
Ritch Melton Avatar answered Oct 06 '22 00:10

Ritch Melton


Change that to a class; all your woes relating to modifying struct properties (etc) will go away.

Alternatively, make it an immutable struct, and initialize it with the correct values at the point of creation - then the issue is moot, no matter how many times it is subsequently copied.

IMO the first is the right approach here.

like image 37
Marc Gravell Avatar answered Oct 06 '22 01:10

Marc Gravell