Home > DeveloperSection > Forums > Is there a way to only add code to a method without overriding it completely in c#?
Kate Smith
Kate Smith

Total Post:24

Points:168
Posted on    September-28-2013 8:14 AM

 C# C# 
Ratings:


 1 Reply(s)
 885  View(s)
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


Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    September-28-2013 9:08 AM

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
         }
    }

Don't want to miss updates? Please click the below button!

Follow MindStick