Matias Cicero
Matias Cicero

Reputation: 26301

How to fix inherited member hiding warning when dealing with virtual properties

I have the following base class:

public class OAuthRefreshToken {

     //Other properties..

     public int UserId { get; set; }
     public virtual OAuthUser User { get; set; }

}

And this derived class:

public abstract class OAuthRefreshToken<U> : OAuthRefreshToken 
         where U : OAuthUser {

     public virtual U User { get; set; }
}

What I want is to override the User property from the OAuthRefreshToken base class with the one in my derived class.

I thought of adding the override keyword:

public override virtual U User { get; set; }

But this throws a compilation error as it is not allowed.

If I leave the code like that (without override) a warning appears saying I'm hiding inherited member (which I intend to do).

It tells me to use override if hiding is intended...

And then we are on a nice loop where the warning tells you do something and the compiler tells you not to do it.

Of course, I'll listen to the compiler, but how can I fix the warning? I don't like building my project and have a nice bunch of warnings appear.

Thank you for your time.

Upvotes: 1

Views: 7195

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502066

The warning should tell you what you can do - something like this (emphasis mine):

'OAuthRefreshToken.User' hides inherited member 'OAuthRefreshToken.User'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

However, presumably you want the two properties to do be about the same value - so you need to also override the property from the base class.

Now, there's a problem because you can't have two properties with the same name but different types declared in the same type... so I'd suggest using a different name for the new property - at which point you don't need to declare it with new because it doesn't hide anything.

public abstract class OAuthRefreshToken<U> : OAuthRefreshToken where U : OAuthUser
{
     public override OAuthUser User
     {
         get { return TypedUser; }
         set { TypedUser = (U) value; }
     }

     public virtual U TypedUser { get; set; }
}

I suspect there may be alternatives where you go back to hiding the property if you introduce an intermediate class, but that's almost certainly going to be even uglier.

Upvotes: 0

Servy
Servy

Reputation: 203827

You can't change the type of the property when overriding it. If you want to change the type, you need to hide the method instead of overriding it. If you want to override it instead of hiding it, you'll need to maintain the same type that the base class uses.

Upvotes: 2

Related Questions