Tuesday, August 03, 2010

How to add method in Sealed class

In Object Oriented world Sealed class is class which can not inherited, its sealed not more implementation get added. This was correct before C#3.0 invented. C#3.0 Comes with lots of new functionality like Extension Methods, Anonymous Types, Partial Methods, Automatic Properties and Object-Collection Initialization. Also there is major portion added to C# 3.0 which is LINQ, you can find Introduction of LINQ here.
So, Sealed class; if we want to add method to any of class then the best way to achieve is to inherit that class and add your own method and going forward you use new derived class all over place. But in case of Sealed you can not do as you cant inherit Sealed class.
To achieve this, we can  use one of the feature of C#3.0, which is Extension Method. Let see with example, following is our Sealed class.
public sealed class User
{
   //Public properties
   public int UserId { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
   //Some of the methods having implementation
   public bool SaveUser() { return true; }
   public bool GetUser() { return true; }
}
Here User is class marked with sealed, which contains few properties and methods operated on it. If we try to inherit User class. It will give you error saying MyUser cannot derived from sealed type ‘User’. Well this is normal behavior if should not allow you to inherit sealed class. But our goal to add new method to Sealed class, so let’s go in that direction.
We are going to use Extension Method added in C#3.0; extension methods are static methods that can be invoked using instance method syntax. The first step of creating extension method is to have static class in which our extension will going to resides. The method which we want is to return Full Name in some specific format. So lets create class and add our method into it.
public static class Extensions
{
   public static string GetFullName(this User usr)
   {
       return string.Empty;
   }
}
Read more: Beyond Realtional