Folks
I have a sealed class as follows. I want to extend this sealed class so as to add a method which will return average of x and y. This is not just extension method using "this" :( Could someone please help me understand the concept of "Extending Sealed class" and its "Real time usage and benefits"
class Sealed A
{
int a; int b;
int Add (int x, int y)
{
return x+y;
}
}
Thank you....
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
The main purpose of a sealed class is to take away the inheritance feature from the class users so they cannot derive a class from it. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.
Sealed classes can be declared directly inside the namespace. We cannot create an instance of a private class. We can create the instance of sealed class. Private Class members are only accessible within a declared class.
As @ReedCopsey has already pointed out, the way to extend the functionality of a sealed class is with an Extension Method. Here is one that will do what you are asking:
public sealed class MyClass
{
int a; int b;
int Add (int x, int y)
{
return x + y;
}
}
public static class MyClassExtensions
{
public static decimal Average(this MyClass value, int x, int y)
{
return (x + y)/2M;
}
}
Usage:
var myClass = new MyClass();
// returns 15
var avg = myClass.Average(10, 20);
EDIT As requested, here is the all the code. Create a new Console Application in Visual Studio, replace all the code in the Program.cs
file with the code below and run.
using System;
namespace ConsoleApplication1
{
public sealed class MyClass
{
public int X { get; private set; }
public int Y { get; private set; }
public MyClass(int x, int y)
{
this.X = x;
this.Y = y;
}
int Add()
{
return this.X + this.Y;
}
}
public static class MyClassExtensions
{
public static decimal Average(this MyClass value)
{
return (value.X + value.Y) / 2M;
}
}
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass(10, 20);
var avg = myClass.Average();
Console.WriteLine(avg);
Console.ReadLine();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With