67

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#

3 Answers 3

127

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.

Sign up to request clarification or add additional context in comments.

7 Comments

@hunter, BUT, how can I access the object variables later without the object being a "var". I can't do x[1].brand.
anonymous types are...anonymous - you can only use them with var, or in C# 4 with dynamic types, otherwise you will have to create a class instance, which works the same way, just add the class name after new and have the class expose the appropriate public properties
edit: I forgot to mention I am trying to do that in a Dictionary<string,Object>
If you're using C# 4.0, you might be able to use the "dynamic" keyword to accomplish what you want. Otherwise, you'll probably need to use a Dictionary<string, string> instead. Historically, C# has not been very good with the sort of dynamic typing you're attempting.
@deadlock unless your data is completely random I would suggest creating some classes. Even using vars within the context of your object[] won't be reference-able from outside of this scope.
|
8

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

1 Comment

Clearly the more better modern answer.
4

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.