It certainly does not break from the standard practice of the .NET framework. When I see a a + b I always assume something new will be created.
static void Main(string[] args)
{
var list = BuildList(ImmutableList<int>.Empty);
var sum = (list + 500).Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
static ImmutableList<int> BuildList(ImmutableList<int> list)
{
if (list.Count < 1000)
{
return BuildList(list + list.Count);
}
return list;
}
Update
See Jon Skeet’s post on what to name methods on immutable lists.
Surprising Responses
I am quite surprised to see so many answers that concur that this makes sense. In principle I also agree but it is way easier for me to read verbose code than it is for someone who is uncomfortable with terseness to read, well terse code. From my working experience they seem to be the majority.
I personally would not recommend overloading operators like
+for any class that isn’t meant to be treated as a primitive. In particular, collections, in my opinion, should never overload operators.Operator overloading makes sense when you have a small immutable class or struct that is meant to behave like a “primitive” type. However, when you start trying to do this for other classes, it really impacts maintainability.
I’d recommend making explicit method calls, instead.
After reading the comments, my recommendation would be to use
Concat()(to match Enumerable.Concat in the Framework). Another option I would prefer would beConstruct(), ala cons (though cons typically prepends), to make the usage very clear: