12

Is there a way in C# to reference a class constructor as a standard function? The reason is that Visual Studio complains about modifying functions with lambdas in them, and often its a simple select statement.

For example var ItemColors = selectedColors.Select (x => new SolidColorBrush(x));, where selectedColors is just an IEnumerable<System.Windows.Media.Color>.

Technically speaking, shouldn't the lambda be redundant? select takes a function accepting a type T and returning type U. The solid color brush takes (the correct) type T here and returns a U. Only I see no way to do this in C#. In F# it would be something like let ItemColors = map selectedColors (new SolidColorBrush).

TL;DR: I guess I'm looking for the valid form of var ItemColors = selectedColors.select (new SolidColorBrush) which doens't require a lamba. Is this possible in C# or does the language have no way to express this construct?

MighMoS
  • 1,228
  • 8
  • 18
  • relevant issue opened https://github.com/dotnet/csharplang/issues/2846 – Sanan Fataliyev Oct 05 '19 at 19:21
  • This question was asked again, six years later, here: https://stackoverflow.com/q/44127501/773113 I would not call that question a duplicate of this one, because that question has been formulated in a more direct, pertinent, and understandable way. – Mike Nakis Jul 20 '21 at 12:55

3 Answers3

10

No you cannot reference a C# constructor as a method group and pass it as a delegate parameter. The best way to do so is via the lambda syntax in your question.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
7

You could lay out a formal method:

private static SolidColorBrush Transform(Color color)
{
    return new SolidColorBrush(color);
}

Then you can use Select like this:

var ItemColors = selectedColors.Select(Transform);
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • +1, This is a construction pattern I have grown to like quite a lot lately, especially for faux-immutability, and in base classes which call methods on their implementors from the static Create(). – Jimmy Hoffa Aug 30 '10 at 15:40
0

I'm not sure I understand you correctly. But are you talking about a factory?

This way you can pass a value to the factory and it will create an instance for you.

SolidColorBrush brush = ColorBrushFactory.BrushFrom(color);

Hope this helped.

Kevin
  • 5,626
  • 3
  • 28
  • 41