Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a base class method

Tags:

I am new to C# and am trying to understand basic concepts. Thank you in advance for your help. I have some sample classes below (typed in this window so there may be some errors)and have two questions:

  1. Is it possible to Call a derived class method that executes the code in the base class method with the same name, then executes the code in the derived class method? Every derived class will need to perform the base class code for the RunCheck then do specialized code specific to its class. I could name RunCheck() something else in the base class and then call it when I call the RunCheck() of the derived class but then I have to remember to call it on the RunCheck() in the derived class.

  2. In the Program.cs I want to output all fields with a blank value if it is on a field that is not in the derived class I pass in. What would I pass in?

Here is my code:

  class baseCheck
  {
      public DateTime StartTime { get; set; }
      public DateTime LastRun { get; set; }
      public int Runs { get; set; }
      //Others

      public void RunCheck()
      {
         if (Started != null)
           started = DateTime.Now;

         LastRun = DateTime.Now;

         Runs++;
      }
    }

    class FileCheck : baseCheck
    {
       public string FileName { get; set; }

       public void RunCheck()
       {
           //I want all the code in the base class to run plus
           //any code I put here when calling this class method

        }
    }
    class DirectoryCheck : baseCheck
    {
       public string DirectoryName { get; set; }

       public void RunCheck()
       {
           //I want all the code in the base class to run plus
           //any code I put here when calling this class method

        }
    }

        //Program.cs
        static void Main()
        {
           //Create derived class - either DirectoryCheck or FileCheck
           //depending on what the user chooses.

            if (Console.ReadLine()=="F")
            {
                FileCheck c = new FileCheck();  
            }
            else
            {
                DirectoryCheck c = new DirectoryCheck();
            }

            PrintOutput(c);

        }
        private void PrintOut(What do I put here?)
        {
           Console.WriteLine("Started: {0}",f.StartTime)
           Console.WriteLine("Directory: {0}", f.DirectoryName)
           Console.WriteLine("File: {0}", f.FileName}
        }
like image 580
NewToCSharp Avatar asked Mar 23 '11 03:03

NewToCSharp


People also ask

How do you extend a base class in Python?

Use the super() Function After Extending a Class in Python When there is a new init() inside a child class that is using the parent's init() method, then we can use the super() function to inherit all the methods and the properties from the parent class.

What does it mean to extend a class python?

In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism.

How do you extend a class in C#?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

How do you override a derived class method?

An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override. Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.


2 Answers

Just call base.RunCheck() in your DirectoryCheck class:

public class DirectoryCheck : baseCheck
{
    public string DirectoryName { get; set; }

    public void RunCheck()
    {
        //I want all the code in the base class to run plus
        //any code I put here when calling this class method
        base.RunCheck();
        Console.WriteLine("From DirectoryCheck");
    }
}

Also with your current implementation you are hiding the base class RunCheck() method - you should really override it - this changes the method signature in the base class to

    public virtual void RunCheck()

and in the derived classes to

    public override void RunCheck()

I suspect what you really want though is something like the Non Virtual interface pattern (NVI) - Expose a protected virtual method in your base class, that child classes can override, but have a public method on the base class that is actually calling that method internally - this approach allows you to extend what you are doing before and after that call.

In your example this would look like this:

class BaseCheck
{
    private DateTime Started { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime LastRun { get; set; }
    public int Runs { get; set; }
    //Others

    public void RunCheck()
    {
        if (Started != null)
            Started = DateTime.Now;

        LastRun = DateTime.Now;
        Runs++;
        CoreRun();
    }

    protected virtual void CoreRun()
    {

    }
}


public class DirectoryCheck : BaseCheck
{
    public string DirectoryName { get; set; }

    protected override void CoreRun()
    {
        //I want all the code in the base class to run plus
        //any code I put here when calling this class method
        Console.WriteLine("From DirectoryCheck");
    }
}
like image 69
BrokenGlass Avatar answered Dec 14 '22 20:12

BrokenGlass


In a derived class, you can call the method in the base class using:

public override void RunCheck()
{
    base.RunCheck();

    // Followed by the implementation of the derived class
}

As mentioned in the comments, the base method will need to be declared as virtual to allow overriding:

public virtual void RunCheck() { ... }

For your PrintOut() method, there is no magic way, but you could have it take the base class as a parameter, and then test for the type.

private void PrintOut(baseCheck f)
{
   Console.WriteLine("Started: {0}", f.StartTime)
   Console.WriteLine("Directory: {0}", f.DirectoryName)

   if (check is FileCheck)
   {
       Console.WriteLine("File: {0}", ((FileCheck)f).FileName}
   }
}

Or you could use overloads:

private void PrintOut(baseCheck f)
{
   Console.WriteLine("Started: {0}", f.StartTime)
   Console.WriteLine("Directory: {0}", f.DirectoryName)
}

private void PrintOut(FileCheck f)
{
    PrintOut((baseCheck)f);

    Console.WriteLine("File: {0}", ((FileCheck)f).FileName}
}

Or you could have your PrintOut method part of your class (maybe even use the existing ToString() method) and override it as required.

like image 22
Xavier Poinas Avatar answered Dec 14 '22 22:12

Xavier Poinas