tags:

views:

87

answers:

3

I recently noticed the following code which basically defines a class method

public Func<string, string> SampleMethod = inputParam =>
{
    return inputParam.ToUpper();
};

which is the same as doing it in the old fashioned way

public string SampleMethod(string inputParam ) 
{
    return inputParam.ToUpper();
}

My question - why would I prefer the first over the second? My eyes are maybe more trained to understand the second style quicker. I find it similar to the difference between SMS lingo and plain old english.

+5  A: 

Those two things are fundamentally different. The former is a field of a delegate type while the latter is really a method. The tiniest difference I can think of is that you can modify the first one dynamically at runtime and assign another method reference to it while the second is fixed.

You shouldn't normally prefer the first over the second if your purpose is to write a simple method for a class in C#.

An example that makes the first extremely fragile:

var c = new SomeClass();
c.SampleMethod = inputParam => inputParam.ToLower();
c.DoSomeTaskThatReliesOnSampleMethodReturningAnUpperCaseString();
c.SampleMethod = null;
c.DoSomeTaskThatCallsSampleMethod(); // NullReferenceException

This style of programming is common in language like Javascript where an object is fundamentally a dynamic creature built upon a simple dictionary.

Mehrdad Afshari
+2  A: 

They are actually not the same at all. The second is a regular member method, that returns ToUpper on the input string.

The first, on the other hand, is a Func member variable, that happens to point to a delegate, that implements the same functionality. However, as this is a method pointer, you can substitute the delegate with any other delegate of the same type at runtime. I.e. you can completely redefine what it means to call this method.

Brian Rasmussen
A: 

One benefit of the second way is it's better from a unit testing perspective - you can test your class and know that the method will correctly return the uppercase string. With the first method, you can change the method at runtime, so unit testing is much harder.

David_001