Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
How do I create a List in a reference?
MyClass classA = new MyClass(); myFuction(new List<MyClass>( ??? ))
How Can I add classA to that new List?
Use
new List<MyClass>() {classA};
For collections, the elements inside the brackets will be executed using the add method (for "regular classes" they will be interpreted as properties)
add
Add a comment
MyClass classA = new MyClass(); myFuction(new List<MyClass>() { classA } ) ;
How about a simple:
List<MyClass> classList = new List<MyClass>(); classList.Add(classA);
You can also work with anonymous data like this:
var myList = new List<object>() { new { Location = 1, Name = "myName"}, new {Location = 2, Name = "myName2" } }
saves you a couple of lines
Use Collection initializers
new List<MyClass>(){classA}
This should work
MyClass classA = new MyClass(); return new List<MyClass>().Add(classA);
When a method is required to pass the list and you have only one item
var apps = GetApps(new List<int> { item.Id });
var apps = GetApps(new List<int> { item.Id })
When you have to add an item in a loop
var appList = new List<App>(); foreach (var savedItem in savedItems) { appList.Add(new App{ Name = savedItem.Name}); }
Required, but never shown
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.
Explore related questions
See similar questions with these tags.