Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: override a property of the parent class

I have a class that inherits from X509Certificate2. I want the NotAfter property to be in UTC rather than local time. I'm pretty new to C# and was wondering if what I have below is the best way of doing it?

internal class Certificate : X509Certificate2
{
    public new DateTime NotAfter 
    {
        get { return base.NotAfter.ToUniversalTime(); }
    }

EDIT When I changed it to this:

public override DateTime NotAfter 
{
    get { return base.NotAfter.ToUniversalTime(); }
}

Resharper complained that "There is not suitable property for override"

like image 273
FunLovinCoder Avatar asked Oct 15 '10 15:10

FunLovinCoder


1 Answers

What you have done there is member hiding. If the class you are deriving from has marked the property as virtual, or is overriding it from it's base (if it has one) you use the override keyword:

public override DateTime NotAfter

The member hiding can be used when the base class has marked it virtual, however if someone cast a reference of your class into the base class and accessed the member, they would bypass your new hiding. With true inheritance using override, this problem does not occur.

As has been noted by someone, this property is not marked virtual:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.notafter.aspx

Member hiding will allow you to get around this if people use your class directly, but the moment someone casts your class back to a base type, they get the base value:

class MyClass : Cert...

MyClass c = new MyClass();
DateTime foo = c.NotAfter; // Your newly specified property.

Cert cBase = (Cert)c;
foo = cBase.NotAfter; // Oops, base value.  Inheritance cures this, but only with virtual members.
like image 141
Adam Houldsworth Avatar answered Sep 22 '22 00:09

Adam Houldsworth