Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# syntax shortcut to skip an object name when refering to it multiple times in a row

Was there any shortcut in c# that would allow to simplify this:

List<string> exampleList = new List<string>();
exampleList.Add("Is");
exampleList.Add("it");
exampleList.Add("possible");

and into something like this:

 var exampleList = new List<string>();
 exampleList {
.Add("is");
.Add("it");
.Add("possible");
}

I know it's possible to assign properties during declaration like this:

var myObject = new MyObject{
Id = "Useful",
Name = "Shortcut"
};

It would be interesting to know if there are other useful shortcuts like that, but I can't find any.

like image 746
CoolCodeBro Avatar asked Jun 29 '13 15:06

CoolCodeBro


2 Answers

var exampleList = new List<string>() {
    "Yes", "kinda", "with", "collection", "initializers" };

Note that you can also do this for multi-parameter Add methods, like dictionaries:

var lookup = new Dictionary<string, int> {
    {"abc", 124}, {"def",456}
};
like image 195
Marc Gravell Avatar answered Nov 14 '22 11:11

Marc Gravell


You could write an extension method:

public static class ListExt
{
    public static List<T> Append<T>(this List<T> self, params T[] items)
    {
        if (items != null && self != null)
            self.AddRange(items);

        return self;
    }
}

And then use it like this:

List<string> list = new List<string>();

list.Append("Or", "you", "can", "use", "an", "extension", "method");

list.Append("Or").Append("like").Append("this");
like image 38
Matthew Watson Avatar answered Nov 14 '22 10:11

Matthew Watson