Overriding behaviour of methods
Below is a pattern to override the implementation of a method in a class – this is especially useful for writing unit tests, e.g. for stubbing out a method behaviour.
internal class MyClass
{
private readonly Func<string, string> DoSomething;
public MyClass()
{
this.DoSomething = DefaultImplementationOfDoSomething;
}
public MyClass(Func<string, string>alternateImplementationOfDoSomething)
{
this.DoSomething = alternateImplementationOfDoSomething;
}
private string DefaultImplementationOfDoSomething(string input)
{
return string.Format("Your input was: {0}", input);
}
public string CallMe(string input)
{
return this.DoSomething(input);
}
}
We can then call our class using the normal constructor or pass through a new implementation of DoSomething.
var myClassDefault = new AlterMethodDynamically();
Console.WriteLine(myClassDefault.CallMe("Hello world"));
Func<string, string> newImplementation = (x) => { return string.Format("BLAH: {0}", x); };
var myClassMethodChanges = new AlterMethodDynamically(newImplementation);
Console.WriteLine(myClassMethodChanges.CallMe("test"));
Explanation of lambda function
System.Func creates a generic delegate – you can then use a lambda function to implement to create the implementation of this delegate (as long as the signature matches what was specified by system.func).
In this example, we use the System.Func<string, string> – this specifies a delegate signature that takes one string as the input parameter and returns a string.
Func<string, string> newImplementation = (x) => { return string.Format("BLAH: {0}", x); };
This effectively implements the delegate a corresponds to a method:
delegate string myMethod(string x);
string newImplementation(string x)
{
return string.Format("BLAH: {0}", x);
}
post a comment / view comments (currently 0 comments)
- Bookmark with:
- Delicious
- Digg
- StumbleUpon