Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a property inherited from an interface become virtual?

Tags:

c#

reflection

Say I have one interface and two classes, and one of the classes implement this 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 does 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 implements 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 does not implement IAAA F1 is not virtual F2 is not virtual AAA2 which implements IAAA F1 is virtual F2 is not virtual 

Any reason for this?

like image 524
runerback Avatar asked Nov 27 '18 03:11

runerback


People also ask

Can we have property in interface?

Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly.

Can I add property in interface C#?

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

Should interface have properties?

Yes, An interface should define properties when it really in need. Please suppose that. There is a IUser interface that has defined a property "Name" then you can use it without worry about if the object didn't implement the property.


1 Answers

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; 
like image 164
vasily.sib Avatar answered Sep 19 '22 14:09

vasily.sib