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?
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.
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.
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!
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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With