Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate Func as a property

How can I pass e.g 2 strings to Func and return a string? Let say I would like to pass FirstName and LastName and the result should be like FirstName + LastName;

Moreover, I would like to have a Func declared as a property.

Please take a look at my code:

public class FuncClass
{
    private string FirstName = "John";
    private string LastName = "Smith";
    //TODO: declare FuncModel and pass FirstName and LastName.
}

public class FuncModel
{
    public Func<string, string> FunctTest { get; set; }
}

Could you please help me to solve this problem?

like image 334
mskuratowski Avatar asked Nov 01 '17 19:11

mskuratowski


People also ask

What is func delegate?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.

What is the use of Func delegate in C#?

Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.

How do you return a value from a delegate?

The key here is using the += operator (not the = operator) and looping through the list that is retrieved by calling GetInvocationList() and then calling Invoke() on each delegate retrieved. Hope this helps!

What is the difference between Func and delegate?

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.


1 Answers

This should do the trick:

public class FuncModel
{
    //Func syntax goes <input1, input2,...., output>
    public Func<string, string, string> FunctTest { get; set; }
}

var funcModel = new FuncModel();
funcModel.FunctTest = (firstName, lastName) => firstName + lastName;
Console.WriteLine(funcModel.FuncTest("John", "Smith"));
like image 86
Himzo Tahic Avatar answered Sep 30 '22 15:09

Himzo Tahic