Home > Enterprise >  C# base misuse?
C# base misuse?

Time:09-22

I quite often find this kind of code in my company...

class Base
{
    public int Property
    {
        get; set;
    }
}

class Derived : Base
{
    public Derived()
    {
        base.Property = 0xAFFE;
    }
}

And, i often argue that this kind of use of base is "wrong".

I argue, that "this.Property" would be "correct" (or simply "Property = 0xAFFE;")

I argue, that one could refactor (making Property virtual, override it).

But, my arguments seem not to convince. Can you help with arguments? Or am i (completely) wrong?

Thanx.

CodePudding user response:

I think that, if Property in your example is not virtual, it doesn't matter if you use base or this. If it is virtual though, and overriden in an inherited class, you'll have differences in behavior.

I personally tend to never use base or this when setting properties like this (which would be the same as specifying this). Only in specific situations (like overriding a virtual method an calling the base implementation) do I use those keywords

CodePudding user response:

So, we have at least 3 ways to say the same:

Property = 0xAFFE;
this.Property = 0xAFFE;
base.Property = 0xAFFE;

And as usual, there are minor aspects that can make a decision why this line is correct or wrong.

First version is most relaxed. Property can be a real property or a variable declared above or a param passed to from outer scope. Moreover, in some cases you can write Property = Property and the compiler would be smart enough to understand you (bad practice anyway).

Second version does an assumption: Property is the class belongings. Period. Despite some code analyzers would rise a hint "syntax can be simplified", this is a normal way of doing things.

Third one intends an assumption that is even more tight: Property is a blessing from ancestors. So even if you override it locally, that syntax 100% ensures you that the change is applied on the ancestor field.

To be honest, in most cases last two syntax forms are interchangeable. Do you really see a point to enforce yours?

  • Related