Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor as a function in C#

Tags:

c#

lambda

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?

like image 723
MighMoS Avatar asked Aug 30 '10 15:08

MighMoS


People also ask

How do you call a constructor function?

These constructors get invoked whenever an object of its associated class is created. It is named as "constructor" because it constructs the value of data member of a class. Initial values can be passed as arguments to the constructor function when the object is declared.

Can we use constructor in function?

Function() constructor The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval() .

Is a constructor considered a function?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

How do you call a class constructor?

Calling a Constructor You call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass(); This example invokes (calls) the no-argument constructor for MyClass as defined earlier in this text.


2 Answers

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.

like image 52
JaredPar Avatar answered Oct 05 '22 23:10

JaredPar


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);
like image 38
ChaosPandion Avatar answered Oct 06 '22 00:10

ChaosPandion