Introduction
Ever want to add some new methodology to your code but don't feel the urge to create a brand new type to do it? Extension methods are your friend! In this blog I'll create a sample extension method and call it through some test case scenarios displayed to the user.
Let's code!
I'll start out by making a sample class called MyExtensionMethodSample. Within it I'll create a string called YourMom which takes a parameter of string. I'll let you read the following source code, bonus points if you get the funny being made :) :
namespace ExtensionMethodsBlogSource { public static class MyExtensionMethodSample { public static string YourMom(this String str) { if (str == null) return "Your Mom should never be null!"; return "It is known"; } } }
Now it's time to use our new extension method. Check out the following code snippet:
using ExtensionMethodsBlogSource; namespace ExtensionMethodsBlogSource { class Program { static void Main(string[] args) { string yourMom = null; Console.WriteLine("1: " + yourMom); Console.WriteLine("2: " + yourMom.YourMom()); yourMom = "YourMom isn't null"; Console.WriteLine("3: " + yourMom); Console.WriteLine("4: " + yourMom.YourMom()); // do the rest Console.WriteLine("\nPress Any Key to Exit."); Console.ReadKey(); } } }
We're starting out with the new string yourMom being null. Writing out some data, it's null so you won't see anything. Calling yourMom.YourMom() should return "Your Mom should never be null!". Setting yourMom to "YourMom isn't null" will display that for the 3rd line. Testing against yourMom.YourMom at this point should give us "It is known".
Output
And our results:
Huzzah, it works as expected. For a real challenge go implement some of this with Pete's named arguments blog from last week and create some coding magic.
No comments:
Post a Comment