I've got following derivations:
interface IMyInterface
{
string myProperty {get;}
}
class abstract MyBaseClass : IMyInterface // Base class is defining myProperty as abstract
{
public abstract string myProperty {get;}
}
class Myclass : MyBaseClass // Base class is defining myProperty as abstract
{
public sealed override string myProperty
{
get { return "value"; }
}
}
I would like to be able to check if a member of a class is declared as sealed. Somewhat like that:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
bool isSealed = property.GetMethod.IsSealed; // IsSealed does not exist
Sense of all this is to be able to run a test, that checks the code/project for consistency.
Following test fails:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsFalse(property.GetMethod.IsVirtual);
It sounds like you want to assert that a method cannot be overridden. In that case You want a combination of the the IsFinal
and IsVirtual
properties:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsTrue(property.GetMethod.IsFinal || !property.GetMethod.IsVirtual);
Some notes from MSDN:
To determine if a method is overridable, it is not sufficient to check that
IsVirtual
is true. For a method to be overridable,IsVirtual
must be true andIsFinal
must be false. For example, a method might be non-virtual, but it implements an interface method. The common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtual final. So there are cases where a method is marked as virtual but is still not overridable.
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