Delegate Func as a property
Asked Answered
C

1

6

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?

Clown answered 1/11, 2017 at 19:50 Comment(6)
Func<string, string, string> is not a "problem".Dogged
It's very unclear what you mean or what you've tried. A Func<string, string> doesn't take two strings, it takes a single string - and it's really unclear where FirstName and LastName would come in here. You could create a Func<string> that returned FirstName + " " + LastName, but that's not the same thing at all, as it has no inputs.Radman
@JonSkeet I would like to have a Func as a property in FuncModel and write a body in FuncClass.Clown
And that much is entirely feasible - but "declare FuncModel and pass FirstName and LastName" make no sense, nor can we tell what the func is really meant to do. What do you want it to return if I call model.FunctTest("unclear") for example?Radman
Func<string, string, string> FullName = (first, last) => first + last; Usage: FullName(FirstName, LastName) Pretty much the same as how you would do delegates just more fancy.Officious
@Cieja - Why are you doing this? What's the underlying problem are you trying to solve?Jeer
W
9

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"));
Waive answered 1/11, 2017 at 20:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.