C# .NET – Why Doesn’t System.String Include a Constructor for IEnumerable?

clanguage-designnet

Why doesn't System.String include a constructor capable of taking a IEnumerable<char>?

The expected behavior would be:

var foo = "hello";
var bar = new string(foo.Select(x => x));

Actual behavior:

Cannot convert from 'System.Collections.Generic.IEnumerable<char>' to 'char*'

If there is no obvious reason, I think it could be a nice pull request.

source: String.cs StringNative.cpp

Best Answer

Since there is a constructor overload that takes an array of characters, this should work:

var bar = new string(foo.Select(x => x).ToArray());

Which pretty much eliminates the need for another constructor overload, as the proposed overload would essentially have to do the same thing.

Eric Lippert often discusses why certain features don't make it into the .NET Framework or the C# language. He says:

The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money.

In other words, every feature must have benefits that exceed those costs, and the .NET Team decided in this instance that the extra constructor was not worth it.

Further Reading
Best way to convert IEnumerable to string?