Advertise with us

Is there a way to only add code to a method without overriding it completely in c#?

Is there any way to only add code to a method from a subclass without overriding it completely like the "override" + "virtual" does in c#. I find myself writing some duplicate code in my override methods. And not sure what to do about it
Last updated:9/28/2013 9:08:24 AM

1 Answers

Samuel Fernandes
Samuel Fernandes

Hello Kate!

You can use override and virtual with a different mechanism. For example,

class MyBase

    {
        private int MyVar;
        public virtual void DoStuff(int i , int j)
        {
            MyVar = i + j; //This is your common code which is added in base class

        }
    }
     class OverridClass : MyBase
    {
        private int MyNewCount;
        public override void DoStuff(int i, int j)
        {
            MyNewCount = i + j;
            base.DoStuff(i, j); //This is how you reuse your common code and write the code which is more specific to this method
         }
    }

Answer