What is sealed class in c# and how to write program

Posted by Jitendrasoft09 under C# on 6/26/2013 | Points: 10 | Views : 1290 | Status : [Member] [MVP] | Replies : 1
Hi All,
I want to understand What is sealed class in c# and how to write program, let me know if anybody knows.

Jitendra Kumar
If my post helps you, plz mark as an answer.



Responses

Posted by: Satyapriyanayak on: 6/26/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET, NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

The following class definition defines a sealed class in C#:


// Sealed class

sealed class SealedClass

{

}

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.


using System;

class Class1

{

static void Main(string[] args)

{

SealedClass sealedCls = new SealedClass();

int total = sealedCls.Add(4, 5);

Console.WriteLine("Total = " + total.ToString());

}

}

// Sealed class

sealed class SealedClass

{

public int Add(int x, int y)

{

return x + y;

}

}

If this post helps you mark it as answer
Thanks

Jitendrasoft09, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response