Should you use a basic keyword?

When calling base class methods from a derived class, should the "base" keyword be used? It seems that using the base keyword would increase the readability of the code, but until now, when I exclude it, there is no effect on compiling and executing the code.

+3
source share
8 answers

You should not use it base, unless you mean "Even if there is a method in this class that overrides the base implementation, I want to call the base implementation and ignore it in this class."

Using basebypasses the virtual sending mechanism, which is so important in polymorphism, invoking a command call, not callvirt.

So speaking base.Foo()very, very different from semantics in words this.Foo(). And you almost always want the latter.

+9
source

The primary keyword is important when overriding methods:

override void Foo()
{
  base.Foo();
  // other stuff
}

I never use it for anything else.

+13
source

, overridden :

class Test { 
   public override string ToString() { return "Hello World"; }
   public string M1() { return ToString(); } // Test.ToString
   public string M2() { return base.ToString(); } // System.Object.ToString
   static void Main() { 
       var t = new Test();
       Console.WriteLine("M1: {0}", M1()); // Hello World
       Console.WriteLine("M2: {0}", M2()); // Test
   }
}
+1

. , base .

( , " / this). " ", , " , , .

+1

, . base - . , base - , ( this), , .

, , , - . , , ( ):

class Base {
   public virtual void Foo() {}
}

class Derived : Base {
   void Bar() { base.Foo(); }
}

-, , :

class MoreDerived : Derived {
   public override void Foo() {}
}

base.Foo() Foo() MoreDerived. , , , .

+1

, , , .

0

:

    class ParentClass {
        public virtual void A() {
            // Some operations
        }
    }

    class ChildClass : ParentClass {
        public override void A()
        {
            base.A();
        }
    }

ChildClass.A(), , :

    class ParentClass {
        public virtual void A() {
            Console.WriteLine("ParentClass.A");
        }
    }

    class ChildClass : ParentClass {
        public override void A()
        {
            A();
        }
    }

StackOverflowException, ChildClass.A() ChildClass.A()

0

In most cases, there will be no difference in the generated IL.

However, if you override the virtual method in the base class or hide the method in the base class using the "new" keyword, then this is necessary and will change the value, since it explicitly calls the base class of the method.

However, this is often a good idea, as it improves readability and therefore maintainability. If you explicitly want to call the method in the base class, then I think this is a good idea, even if it is not technically required.

-1
source

Source: https://habr.com/ru/post/1719418/


All Articles