Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you inherit from a sealed class using reflection in .Net?

Tags:

Before you start firing at me, I'm NOT looking to do this, but someone in another post said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things...

like image 940
Kilhoffer Avatar asked Sep 30 '08 21:09

Kilhoffer


People also ask

Can I inherit a sealed class in C#?

A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated.

What is the benefit of sealed class in C#?

The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.

Can a sealed class implement interface?

enum classes can't extend a sealed class (as well as any other class), but they can implement sealed interfaces.


1 Answers

Without virtual functions to override, there's not much point in subclassing a sealed class.

If you try write a sealed class with a virtual function in it, you get the following compiler error:

// error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal' 

However, you can get virtual functions into sealed classes by declaring them in a base class (like this),

public abstract class Animal {     private readonly string m_name;      public virtual string GetName() { return m_name; }      public Animal( string name )     { m_name = name; } }  public sealed class Seal : Animal {     public Seal( string name ) : base(name) {} } 

The problem still remains though, I can't see how you could sneak past the compiler to let you declare a subclass. I tried using IronRuby (ruby is the hackiest of all the hackety languages) but even it wouldn't let me.

The 'sealed' part is embedded into the MSIL, so I'd guess that the CLR itself actually enforces this. You'd have to load the code, dissassemble it, remove the 'sealed' bit, then reassemble it, and load the new version.

like image 52
Orion Edwards Avatar answered Oct 21 '22 08:10

Orion Edwards