Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 281

C#.Net Sealed Classes and Sealed Methods

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. Sealed classes may not be used as a base class, We have to create object of the class to access its member.

Example 1: Sealed class declaration

sealed class Class1
{
    public void method()
    {
        Console.WriteLine("This is a method");
    }
}

class Class2 : Class1 // Error: cannot be inherited
{
    public void method2()
    {
        Console.WriteLine("This is a method2");
    }
}

Example 2: Sealed class declaration

namespace SealedClass
{
    sealed class Class1
    {
        public void method()
        {
            Console.WriteLine("This is a sealed class method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 obj = new Class1();
            obj.method();
            Console.Read();
        }
    }
}

Sealed methods are those method that cannot be overridden.

Example 3: Sealed methods declaration

namespace SealedMethod  
{  
    class Program  
    {  
        public class BaseClass  
        {  
            public virtual void Display()  
            {  
                Console.WriteLine("Virtual method");  
            }  
        }  
        public class DerivedClass : BaseClass  
        {  
            // Now the display method have been sealed and can;t be overridden  
            public override sealed void Display()  
            {  
                Console.WriteLine("Sealed method");  
            }  
        }  
        //public class ThirdClass : DerivedClass  
        //{  
        //    public override void Display()  
        //    {  
        //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");  
        //    }  
        //}  
        static void Main(string[] args)  
        {  
            DerivedClass ob1 = new DerivedClass();  
            ob1.Display();  
            Console.ReadLine();  
        }  
    }  
}