How to declare a inline object with inline variables without a parent class
I am trying to do something like:
Object [] x = new Object[2];
x[0]=new Object(){firstName="john";lastName="walter"};
x[1]=new Object(){brand="BMW"};
I want to know if there is a way to achieve that inline declaration in C#
yes, there is:
object[] x = new object[2];
x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };
you were practically there, just the declaration of the anonymous types was a little off.
You can also declare 'x' with the keyword var:
var x = new
{
driver = new
{
firstName = "john",
lastName = "walter"
},
car = new
{
brand = "BMW"
}
};
This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :
x.driver.firstName // "john"
x.car.brand // "BMW"
var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"