IS THERE A WAY TO ONLY ADD CODE TO A METHOD WITHOUT OVERRIDING IT COMPLETELY IN C#?

Kate Smith

Total Post:24

Points:168
Posted by  Kate Smith
C# 
C#
 1173  View(s)
Ratings:
Rate this:
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
  1. Samuel Fernandes

    Post:159

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

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!