Sealed modifier in C# example.

This is short tutorial about sealed modifier in C#.

  1. Few important things to note about sealed class:
  2. Sealed class cannot be inherited.
  3. You cannot use abstract modifier with sealed class.
  4. Every struct is sealed, therefore it can not be inherited and become base for other class.

MODEL

public sealed class Rectangular
{
    public int x;
    public int y;

    public int Area()
    {
        return x * y;
    }
}

public class Circle: Rectangular { } // This will fail, as Rectangular class is sealed and cannot be base for any other class

CONTROLLER

Rectangular sclass = new Rectangular();
      
        sclass.x = 15;
        sclass.y = 10;

        sclass.Area();

        ViewData["RectangularArea"] = String.Format("Side a is {0}, side b is {1}, area of rectangular is {2}", sclass.x, sclass.y, sclass.Area());


VIEW

  @if (ViewData["RectangularArea"] != null)
  {
<h3>@ViewData["RectangularArea"]</h3>
  }

Try to create new class in your model :

public class Circle : Rectangular { }

you will get this error:


Comments