tags:

views:

82

answers:

3

I wasn't sure how to title this question correctly but here is what i'm trying to do.

Say I have a class Customer that has an ID, firstName, and lastName field. Now say I have a list of customers and I want to write one method that will write ID, firstName, OR lastName to the console depending on which one I specify.

In essense, I would like to write one method that accepts the field I would like to print out instead of writing three seperate methods to print out each field type.

I know I have read about how to do this in C# over the past few days but my brain is on overload and it is slipping my mind....

Any help would be appreciated.

+10  A: 
public void PrintCustomer<T>(Customer c, Func<Customer, T> func)
{
   Console.WriteLine("{0} , {1}", c.ID, func(c));
}

Usage:

PrintCustomer(myCustomer, c => c.FirstName);

OR

PrintCustomer(myCustomer, c => c.LastName);
BFree
functional programming rules!!!
CrazyJugglerDrummer
I added what I consider to be an improvement on this solution in another answer...
Scott Munro
A: 

Use an Enum as an argument? Each enum value is a different target field...

gmagana
A: 

This is really just a comment on BFree's answer but I wanted to have syntax highlighting...

The type of the return value can be hidden from client code using the following signature. I would consider this an improvement.

public static void PrintCustomer(Customer c, Func<Customer, string> func)
{
    Console.WriteLine("{0} , {1}", c.ID, func(c));
}
Scott Munro
Then don't you have to type "PrintCustomer(myCustomer, c => c.ID.ToString());" instead of "PrintCustomer(myCustomer, c => c.ID);" if Customer.ID is an integer?
Kevin