Monday 27 July 2015

Sealed Classes & Extension methods

We've talked a lot about scope as of late: public, private, protected, internal and protected internal, well here's an an interesting thing we can do to a class, we can seal it


public sealed class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

//Compile time error: 'Employee' cannot derive from sealed type 'Person'
class Employee : Person { }


By setting the Person class as sealed we can no no longer inherit from it, meaning our employee class cannot inherit from person. Now I've never come across an instance in which I've wanted to do this, but I have come across sealed classes. Luckily there is a way to extend them, and that's by creating extension methods.

our extension methods have to reside in a Static class and must reference the type they're extending using "this" keyword.


namespace pc.sealingAndExtending
{
    public sealed class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    static class ExtensionMethod
    {
        //Notice the 'this' keyword in the argument for the extension method
        public static string GetFullName(this Person p)
        {
            return $"{p.FirstName} {p.LastName}";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Person { FirstName = "Pawel", LastName = "Ciucias" };
            System.Console.WriteLine(p.GetFullName());
        }
    }
}

You can also create extension methods for classes that are not sealed, but this is not a good practice, generally extension classes are a last resort. If you need to extend a class and it's not sealed you should leverage inheritance.