Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override a Method in a Base Class within the same Class (NOT a Derived Class)?

Tags:

c#

.net

oop

asp.net

My understanding is that it is possible to Override a method (marked as Virtual) in a base class from a derived class using the keywords override.

But what about overriding a method in the same class?

In my specific case, I have a class x with 2 methods. Method a has some common behavior with b, and b adds functionality to method a.

In the past, I have duplicated the code of a in b and added the new functionality into b.

I would like to know if there is a better approach so I can centralize the behavior of method a.

    public class x
    {
       public static void a() {}
       public static void b() {}         
    }
like image 438
GibboK Avatar asked Jun 09 '11 07:06

GibboK


2 Answers

You could simply call your method a() from within your method b(). No need (and no way) to override a method.

public class x
{
   private static int _i = 0;

   public static void a() {
       _i = 1;
   }
   public static void b() {
       a();
       // here is _i = 1;
   }         
}

On the other hand you could have parameter overloads for your method.

public class x
{
   private static int _i = 0;

   public static void a() {
       a(1);
   }
   public static void a(int i) {
      _i = t;
      // common code which can use _i
   }         
}

In this case you can call a(1) or a() with the same result.

like image 72
DanielB Avatar answered Sep 30 '22 18:09

DanielB


You can't override in the same class, you only do that in the derived class. You could put the common behavior of your method in method a and then call it from method b.

public static void a() 
{
// some common functionality
}

public static void b()
{
// do something
a(); //call a
//do something else
}

You're free to call a from within b as many times as needed.

like image 25
Tony The Lion Avatar answered Sep 30 '22 16:09

Tony The Lion