1

As we know that a simple array can be initialized like this for example, int [] TestArray = {1,2,3,4}, but how about if we use an array with a structure object and we want to initialize it?

I know that we can access the structure object array like this for example,

Suppose struct Automobile is our structure and we have field in it such as public int year , public string model and we create an array structure object for example, Automobile [] Car = new Automobile(); so we can access the element of a structure array object and give it a value if we use it with structure field for example, Car[2].year = "2016"and then can display it in for example,

MessageBox.Show(Car[2].year.ToString()); 

But what if we want our structure array object to having initial values like we have it in normal array initialization as written in the start?

Anonymous
  • 489
  • 1
  • 7
  • 18

2 Answers2

3

Try

var auto = new[]
        {
            new Automobile {year = 1984, model = "charger"},
            new Automobile {year = 1985, model = "challenger"},
            new Automobile {year = 1984, model = "hemicuda"}
        };

var auto = new[] is shorthand for Automobile[] auto = new Automobile[] which you can use instead if you're more comfortable with it.

Ash
  • 5,786
  • 5
  • 22
  • 42
2

Let the Structure be defined as like this:

public struct Automobile
{
    public int Year { get; set; }
    public string model { get; set; }
}

Then you can create the array of this structure variables like the following:

Automobile[] AutomobileList = new Automobile[] { 
                               new Automobile() {Year=2015,model="Some model1" },
                               new Automobile() {Year=2014,model="Some model2" },
                               new Automobile() {Year=2013,model="Some model3" }};

Similar way you can define a list too;

List<Automobile> AutomobileList = new List<Automobile>() { 
                                   new Automobile() {Year=2015,model="Some model1" },
                                   new Automobile() {Year=2014,model="Some model2" },
                                   new Automobile() {Year=2013,model="Some model3" }};
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • What is `get; set` and why you used it when it worked without it as well? Can you share your knowledge with us? – Anonymous Jul 18 '16 at 05:21
  • @GhostRider - Have you not seen `get; set;` before? – Enigmativity Jul 18 '16 at 05:22
  • 1
    That are used to define Properties, You can use this Thread to understand the [Difference between Variables and properties](http://stackoverflow.com/questions/4142867/what-is-difference-between-property-and-variable-in-c-sharp) – sujith karivelil Jul 18 '16 at 05:27