Part-12 Sealed Class & Struct Class


Sealed Class

A Sealed class is a class  that cannot be inherited and used to restrict the properties.A class can be sealed by using the sealed keyword.

Example:- if we seal class A as below source code then class B cannot be derived from it. One question arises immediately that can we create object of sealed class in C# program? Answer is, of course we can create object of sealed class. Purpose of sealed class is only to prevent a class to be inherited.


sealed class A

{
}
//derive B from A
//Compile error : 'B' cannot derive from sealed type 'A'
class B : A
{
} 

Some points to remember:

  1. This sealed class cannot contain abstract methods.
  2. sealed class itself means that no class can be derived or extended from it.
  3. we can create object of a sealed class.
  4. we can consume the class from sealed class inheritance of the class.

Example :


    class Check
    {
    }
   sealed class Test : Check
    {
    }

Program sealed class


  public sealed class Demo
    {
        private int x;
        private int y;

        public int Add(int x, int y)
        {
            return x + y;
        }
    }  
    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();
            int result = demo.Add(10, 24);
            Console.WriteLine("Total Calculation :"+ result);
            Console.Read();
        }
    }

Struct Class :

Structs are mainly useful to hold small data values. A structure can be defined using the struct keyword. 


Some points to remember:

  1. Structs are value types allocated either on the stack
  2. Struct cannot have a default constructor .
  3. A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.

struct  Check   
 {
  }
 struct  Test : Check
    {
    }

Output :-
Type 'Check' in interface list is not an interface

4. Structure can implement interfaces, same as class.   
                                                       
 interface I1  
   { 
   }
   struct  Check : i1
   {  
   }
Example :-
struct Program
{
    int x, y;
    Add(int x, int y)
    {
    }
}