Why a property inherited from interface became virtual?

  • A+
Category:Languages

Say I have one interface and two classes, one of the class implement that interface:

interface IAAA {     int F1 { get; set; } }  class AAA1 {     public int F1 { get; set; }     public int F2 { get; set; } }  class AAA2 : IAAA {     public int F1 { get; set; }     public int F2 { get; set; } } 

In class AAA2, property F1 is 'inherited' (I'm not sure) from interface IAAA, then I use reflection to check whether a property is virtual:

Console.WriteLine("AAA1 which not implement IAAA"); foreach (var prop in typeof(AAA1).GetProperties()) {     var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";     Console.WriteLine($@"{prop.Name} is{virtualOrNot} virtual"); }  Console.WriteLine("AAA2 which implemented IAAA"); foreach (var prop in typeof(AAA2).GetProperties()) {     var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";     Console.WriteLine($"{prop.Name} is{virtualOrNot} virtual"); } 

the output is:

AAA1 which not implement IAAA F1 is not virtual F2 is not virtual AAA2 which implemented IAAA F1 is virtual F2 is not virtual 

any reason for this?

 


As from remarks section of MS docs:

A virtual member may reference instance data in a class and must be referenced through an instance of the class... 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

If you need to determine whether this method is overridable then checking IsVirtual is not enough and you need to also check that IsFinal is false.

Here is an extension method that do this check:

public static bool IsOverridable(this MethodInfo method)     => method.IsVirtual && !method.IsFinal; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: