0

I am trying to find out the syntax to add a complex object into a list. Here's what I know works:

ComplexObject temp = new ComplexObject() {attribute1 = 5, attribute2 = 6};
ComplexObjectList.Add(temp);

Here's what I'm wanting to do instead:

ComplexObjectList.Add(new ComplexObject(){attribute1 = 5, attribute2 = 6});

I realize that it doesn't work, but is there any other way to add one to my list without creating one before hand? I have no need for temp other than this one function call.

12
  • 8
    " realize that it doesn't work" But it works this way. Commented Jul 20, 2012 at 20:53
  • What doesn't work? Your syntax looks fine to me. Commented Jul 20, 2012 at 20:53
  • How can you insert something that you have never created Commented Jul 20, 2012 at 20:54
  • 1
    Note that even if your code looks like the "what I'm wanting to do instead" example (which is legal, as others have noted), the compiler will still create the temp variable implicitly. Commented Jul 20, 2012 at 21:22
  • 1
    I guess the main point is, the OP should let us know what his error was. Assuming his 1st example compiled, so should his second. Commented Jul 20, 2012 at 21:25

2 Answers 2

3

Assume you have this class (main point being must be an accessible constructor and the properties you wish to set must be visible):

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

And you have this list:

var listOfPoint = new List<Point>();

Then you can, as your second example ponders, do this:

listOfPoint.Add(new Point { X = 13, Y = 7 });

Which is roughly (there are some slight differences, Eric Lippert has some good reads on this) equivalent to your first example:

var temp = new Point { X = 13, Y = 7 };
listOfPoint.Add(temp);

In fact, you could add the point at the time the list is constructed as well:

var listOfPoint = new List<Point>
    {
         new Point { X = 7, Y = 13 }
    };

Now the fact that you say you "realize that it doesn't work" is puzzling because your initializer syntax is correct, so I'm not sure if you're asking before trying it, or if there is an issue with the declaration of your list or your class that is throwing you off. That said, if your first code snippet compiled, technically so should your second.

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

Comments

1

Your code should work. If not, then the problem is probably in the declaration of ComplexObjectList. Should be: List<ComplexObject> ComplexObjectList = new List<ComplexObject>(); Also make sure the class properties are public.

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.