If a type is accessible and unsealed, it will be possible for outside code to create instances of that type and there isn't really anything the base type can do about it. No "full trust" or Reflection required.
public class CantDeriveMe
{
private CantDeriveMe()
{
}
public override string ToString()
{
return "My type is " + this.GetType().ToString();
}
}
public class OhYeah : CantDeriveMe
{
static OhYeah CapturedInstance;
~OhYeah()
{
CapturedInstance = this;
}
OhYeah() : this(1/String.Empty.Length)
{
}
OhYeah(int blah) : this()
{
}
public static OhYeah Create()
{
try
{
new OhYeah(4);
}
catch (DivideByZeroException)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return CapturedInstance;
}
public static void test()
{
OhYeah it;
it = OhYeah.Create();
Console.WriteLine("Result was ({0})", it);
}
}
Note that if code is written only in C#, a base-class destructor might squawk if it notices that the object isn't of a legitimate type, but code written in languages other than C# would allow the override of Finalize
to exit without chaining to its parent.
I think it's possible to specify an open generic interface with a combination of struct
and class constraints which no combination of types could possibly fulfill, e.g.
public interface evil
where T : struct,U
where U : class
I'm not sure whether such an open-generic type would really qualify as an "interface", though, or whether only closed generic types can really qualify as interfaces (or classes, or structs).