2

When looking at the reflected PropertyInfo of a class, I find that properties are marked as virtual when they implement an interface that declares that property.

class Program
{
    public interface IWhatever
    {
        long? Id { get; set; }
    }

    public class Whatever : IWhatever
    {
        public long? Id { get; set; }
    }

    static void Main(string[] args)
    {
        var properties = typeof(Whatever)
            .GetProperties()
            .Where(_ => _.GetMethod?.IsPublic ?? false)
            .Where(_ => !_.GetMethod.IsVirtual)
            .Where(_ => _.SetMethod?.IsPublic ?? false)
            .Where(_ => !_.SetMethod.IsVirtual)
            .Select(_ => _.Name)
            .ToArray();

        Console.WriteLine(string.Join(", ", properties));
    }
}

If I run that code, no properties are reported, because Id Get/Set are marked with IsVirtual. If I remove the interface, Id is returned because it IsVirtual is false. While this must be a language feature, I am wondering why?

It would be nice to be able to determine if a property was specifically declared as virtual, instead of just being virtual by nature of making use of one or more interfaces. What is the reasoning behind this behavior?

Smack Jack
  • 257
  • 4
  • 16

0 Answers0