Saturday, January 12, 2013

What is sealed in c#?


Sealed Class

Sealed is the keyword that used with the class to prevent it from Inheritance i.e. no one class can be derived from a sealed class.

Note: Sealed keyword can not be used with the class variables.


Example -

    sealed class MyClass
    {
        public string DisplayName()
        {
            return "Sachin";
        }
    }

    class SealedClass
    {
        static void Main()
        {
             //Correct way to use sealed class.
            MyClass obj = new MyClass();
            Console.WriteLine(obj.DisplayName());

            Console.ReadLine();
        }
    }

     // Not Correct. It will give compilation error.
    class test : MyClass
    {

    }            
 
        Compilation Error - 'WindowsFormsApplication1.test': cannot derive from sealed type 'WindowsFormsApplication1.MyClass' 


No comments:

Post a Comment