tags:

views:

66

answers:

4

I want to pass a List into a method, but I only want it to contain 1 item.

Is it possible for me to do this similar to

MyType myType = new MyType();
MyMethod(new List<MyType>{ myType }); // somehow add myType to the list as I'm creating it
+2  A: 

I was wrong, the short answer wasn't missing parenthesis in the example as it was posted. There must have been some other typo because all of the following worked when I tested it:

MyType myType = new MyType();
MyMethod(new List<MyType>{ myType }); 

MyMethod(new List<MyType>{ new MyType(), new MyType() }); 

MyMethod(new List<MyType>{ new MyType() }); 

======================== Short answer: You are missing the parenthesis.

MyType myType = new MyType();
MyMethod(new List<MyType>(){ myType }); 

or if you don't need the variable named myType around beyond inserting (such that it will only be used from the list)

MyMethod(new List<MyType>(){ new MyType(), new MyType() }); 

Note the example directly above inserts two items in the list. I wrote it that way to show multiple creations. If you just wanted one as you indicated in your question then this is what you should use:

MyMethod(new List<MyType>(){ new MyType() }); 
Felan
They are not needed, so his code should be working.
Draco Ater
I guess I'd never tried it without the parenthesis before.
Felan
+1  A: 

You're missing the brackets. This should work.

MyMethod(new List<MyType>() { myType });
Cameron MacFarland
Brackets are not needed actually, so his code should work perfectly.
Draco Ater
+3  A: 

Look here for a complete clarification on a subject.

n535
A: 

These are just object/collection initializers, as pointed out. One suggestion is that before you go crazy with inline object definitions, install and bow to the gods of StyleCop for advice writing readable/sustainable code. It helps my coworkers not kill me.

Marc Bollinger