Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify scope?

Consider this code sample:

public abstract class Parent
{
    public int val;
    public Parent()
    {
        val = 0;
    }
    public virtual void foo()
    {
        inc();
    }

    public virtual void inc()
    {
        val = val + 10;
    }
}

public class Child : Parent
{
    public override void foo()
    {
        base.foo();
    }

    public override void inc()
    {
        val++;
    }
}

static void Main(string[] args)
{
    Parent p = new Child();
    Console.WriteLine("p.val = " + p.val);  //Output: p.val = 0
    p.foo();
    Console.WriteLine("P.val = " + p.val);  //Output: p.val = 1
}

I am assuming the inc() of the Parent class did not get called because {this} pointer is actually pointing to a Child object so the Child's version of inc() will be called from the Parent object's function foo(). Is there a way to force the Parent's function foo() to always call parent's function inc() Like you could in C++ with :: operator?

like image 338
Nickolay Kondratyev Avatar asked Dec 09 '22 02:12

Nickolay Kondratyev


1 Answers

No, the only way you can call a virtual method non-virtually is with base.Foo. Of course, you could write a non-virtual method in Parent, and make Parent.foo() call that, as well as the default implementation of Parent.inc().

like image 110
Jon Skeet Avatar answered Dec 22 '22 01:12

Jon Skeet