Reputation: 8826
How can I modify the following code:
var people = new[] {
new { name = "John", surname = "Smith" },
new { name = "John", surname = "Doe" },
};
To not use the var
keyword (so I can initialise the variable in an object initialiser) and still be able to access the elements like this?:
System.Console.WriteLine(people[0].surname); //John
System.Console.WriteLine(people[1].surname); //Doe
Upvotes: 0
Views: 59
Reputation: 1038800
Define a model:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
and then have a collection of this model
:
List<Person> people = new List<Person>();
people.Add(new Person { Name = "John", Surname = "Smith" });
people.Add(new Person { Name = "John", Surname = "Doe" });
or:
var people = new List<Person>
{
new Person { Name = "John", Surname = "Smith" },
new Person { Name = "John", Surname = "Doe" }
};
and then you can still:
System.Console.WriteLine(people[0].Surname); //John
System.Console.WriteLine(people[1].Surname); //Doe
Upvotes: 5
Reputation: 9049
You could use 'dynamic'
dynamic people = new[] {
new { name = "John", surname = "Smith" },
new { name = "John", surname = "Doe" },
};
And then call it
Console.WriteLine(people[0].name);
Note - Works on framework 4.0 onwards, also comes with the caveats mentioned already.
Upvotes: 1
Reputation: 203820
First you'll need to create a named type for that data:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
Then use that type when creating the array:
People[] people;
//...
people = new People[]{
new Person{ Name = "John", Surname = "Smith" },
new Person{ Name = "John", Surname = "Doe" },
};
Upvotes: 2
Reputation: 437376
You cannot; you will have to define a proper class for these objects or reuse one (e.g. Tuple
).
Technically the one-word change from var
to dynamic
will also do the trick, but of course this changes the essence of the member dramatically so it's not equivalent by any stretch of the imagination.
Upvotes: 5