Tiana987642 Tiana987642 - 3 months ago 11
C# Question

Reuse method code on derived class

I have a base class like this

using System;
public class Message{
public int id {get;set;}
//a lot of properties here
public void print(){
Console.WriteLine("id is " + id );

//a lot of write lines here
}
}


and a derived one like this

public class Comment : Message{
public int parent_id {get;set;}
//a lot of properties here
public void print(){
//???
}
}


How to implement method
print()
of
Comment
which can reuse code of
Message::print()
?

Here is code on ideone https://ideone.com/9af6UM

Answer

Depending on what you want to do, call the base class:

public void print()
{
    base.print();
}

Or override the base function:

// Message class:

public virtual void print()
{
    // Code...
}

// Comment class:

public override void print()
{
    // Some code...
}

Update: A C++ translation, as requested. Calling the base class:

public:
void print() {
    Message::print();
}

Overriding the base function:

// Message class:

public:
virtual void print() {
    // This line is the same as Console.WriteLine()
    // std::cout << "id is" << id << std::endl;

    // Code...
}

// Comment class:

public: 
void print() override {
    // Some code...
}
Comments