.net 3.5 - Assign a list of values to a struct in C#? -
i have struct (.net 3.5):
struct columnheadings { public string name ; public int width ; } ;
and when try assign list of values struct 'cannot implicitly convert type string/int ...':
private void dosomething() { columnheadings[,] ch = new columnheadings[,]{{"column1",100}, {"column2",100},{"column3",100}}; }
can struct values assigned in same way multi-dimensional array? or need assign values using?:
ch.name = "column 1";
update:
thanks marc's excellent feedback correct solution is:
struct:
struct columnheadings { private readonly string name; private readonly int width; public string name { { return name; } } public int width { { return width; } } public columnheadings(string name, int width) { this.name = name; this.width = width; } }
then in method:
var ch = new[]{new columnheadings("column1",100), new columnheadings("column2",100), new columnheadings("column3",100)};
and link why mutuable structs aren't idea.
firstly, shouldn't struct
at all
the syntax be:
columnheadings[] ch = new columnheadings[]{ new columnheadings{name="column1",width=100}, new columnheadings{name="column2",width=100} };
however, in addition have issue of public fields, , fact mutable struct - both of dangerous. no, really.
i add constructor:
var ch = new []{ new columnheadings("column1", 100), new columnheadings("column2", 100) };
with:
struct columnheadings { private readonly string name; private readonly int width; public string name { { return name; } } public int width { { return width; } } public columnheadings(string name, int width) { this.name = name; this.width = width; } }
Comments
Post a Comment