Description of overload of Virtual Methods in C #

Source: Internet
Author: User
First, let's take a look at the example below,
Using system;

Abstract Public class contact
{
Public Virtual string prinf ()
{
Return ("this is a virtual method ");
}
}

Public class class1: Contact
{
Public String prinf ()
{
Return ("this is a new method"); // but this will cause a compilation warning, because a method with the same name has been inherited from the contact.
}
}
To compile the file, you only need to change the prinf statement
Public override string prinf ()
Or
Public New String prinf ()
However, the two statements are different,
See the following example:
Using system;

Abstract Public class contact
{
Public Virtual string prinf ()
{
Return ("this is a virtual method ");
}
}

Public class class1: Contact
{
Public override string prinf ()
{
Return ("this is a new method ");
}
}
Public class class2: Contact
{
Public New String prinf ()
{
Return ("this is another new method ");
}
}
Public class text
{
Public static void main ()
{
Contact [] contacts = new contact [2];
Contacts [0] = new class1;
Contacts [1] = new class2;
Foreach (contact CT in contacts)
{
Console. writeline (Ct. printf );
}
}
}

The final result is:

This is a new method.
This is a virtual Method

I didn't see "this is another new method", because class2 didn't reload the virtual method, but instead redefined a method!
This is the difference between the two !!! # C # column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.