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.
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}
};
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With