Archive for category Design Patterns
With traditional object oriented development, extending objects (classes) is normally achieved by deriving class from base class and placing extra functionality there.
but some times you are not allowed to extend classes (marked not extendible sealed/NotInheritable, as a result there is no way to extend these classes although you can still use some patterns like decorator to achieve the goal but the hard way.
A good example of this is System.String class as its non extendible
To solve this issue the easy way Microsoft implemented Decorator pattern in the form of Extension Methods in Dotnet framework 3.5, it lets you extend any existing type’s functionality even when a type is non extendible
How to create Extension Method
lets create a sample for Extension Methods, we will extend String class and will provide 3 extension methods namely
- Is Valid (just verifies instant of the string returns true/false
- ToString (will talk about this one later)
- ToAlternateString (this will return a simple string)
lets start (I am using c# for this example):
- Create a C# console application
- Create a new class as in my example I have named it “Extensions” with the namespace “StringExtensions” and mark the class as “static”
- Create the 3 methods we talked about above and mark them as static too.
- now here comes the real trick the first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier e.g. in my case
you can see that in the parameter I have added this and after that the objecttype which in my case is string, it ensures that this method will work only on string type objects.
Do note that Extension Methods can not access any private data in the extended class.
- here is my Extensions class
- here is my Program class
- Now execute the program
you will notice that Isvalid and ToAlternateString methods are working fine but “ToString()” method we extended it is not working as our output was supposed to be “To String method Extended” but in this case its the actual value.
That is the one of the beauty of Extension Methods “An extension method will never be called if it has the same signature as a method defined in the type/Instance.”
there are some other topics related to this which I will cover later.