How to Automatically Add Item to a List As I'm Creating It?
I want to pass a List into a method, but I only want it to contain 1 item开发者_Go百科.
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
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() });
You're missing the brackets. This should work.
MyMethod(new List<MyType>() { myType });
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.
精彩评论