cmonti
cmonti

Reputation: 187

How do I convert this delegate into a function?

I have this delegate:

Func<Employee, string> format = e =>
     string.Format( "{0} - {1}, {2}",
       e.Number, e.LastName, e.FirstName
);

I'm going to use it in two different methods the same way, instead of repeating the code, I want to create a private method to handle this. How can I create a private method that do exactly the same?

Upvotes: 0

Views: 55

Answers (3)

ryanyuyu
ryanyuyu

Reputation: 6486

A func is a method that take one input and returns an output.

private string MethodName(Employee e)
{
    return string.Format("{0} - {1}, {2}",
         e.Number, e.LastName, e.FirstName);

}

Note that you can also use the statement lambda instead of a lambda expression. The statement lambda has the same method body as the named one above.

e => {
         return string.Format( "{0} - {1}, {2}",
              e.Number, e.LastName, e.FirstName);
     }

Upvotes: 1

juharr
juharr

Reputation: 32266

public static string FormatEmployee(Employee e)
{
    return string.Format( "{0} - {1}, {2}", e.Number, e.LastName, e.FirstName);
}

But really this sounds like it should be a method in the Employee class, or if you don't have access to edit that class then you can make it an extension method.

public static string FormatEmployee(this Employee e)
{
    return string.Format( "{0} - {1}, {2}", e.Number, e.LastName, e.FirstName);
}

Upvotes: 5

Martin
Martin

Reputation: 397

private string FormatEmployee(Employee e) 
{
return string.Format("{0} - {1}, {2}",
       e.Number, e.LastName, e.FirstName);
}

?

Upvotes: 1

Related Questions