4

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?

0

7 Answers 7

8

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)

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

Comments

3
MyClass classA  = new MyClass();

myFuction(new List<MyClass>() { classA } ) ;

Comments

2

How about a simple:

List<MyClass> classList = new List<MyClass>();
classList.Add(classA);

5 Comments

I think the OP wants to inline it into the method call.
@DStanley, while true, I would prefer this method myself. Also this is the only post that is different.
This is the neater way to do it imho, but that will always be a point of discussion amongst coders.
Why write three lines of code when you can write one that's just as readable?
Because it looks a lot neater when you ulscale the
1

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

Comments

1

Use Collection initializers

new List<MyClass>(){classA}

Comments

0

This should work

MyClass classA = new MyClass();
return new List<MyClass>().Add(classA);

Comments

0
  • When a method is required to pass the list and you have only one item

    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});
       }
    

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.