Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a classes Property or Method is declared as sealed

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);
like image 282
Markus Weber Avatar asked Jun 28 '16 14:06

Markus Weber


Video Answer


1 Answers

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 and IsFinal 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.

like image 185
D Stanley Avatar answered Sep 23 '22 14:09

D Stanley