Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealing abstract class or interface in .NET class

Tags:

c#

.net

In Scala, it is possible to have define a base class or trait(interface) sealed, so that the only classes which are allowed to extend that class must be placed in the same class.

This is a useful pattern when coding libraries, is there any equivalent in .NET?

like image 264
Edmondo1984 Avatar asked Jul 10 '13 07:07

Edmondo1984


1 Answers

The only way to simulate that is to have a private constructor in the abstract class and provide implementation as nested classes.

Example

public abstract class Foo
{
  private Foo(int k) {}

  public class Bar : Foo
  {
     public Bar() : base(10) {}
  }
}
like image 70
leppie Avatar answered Oct 15 '22 13:10

leppie