C# Error CS0508 – ‘Type 1’: return type must be ‘Type 2’ to match overridden member ‘Member Name’

C# Compiler Error

CS0508 – ‘Type 1’: return type must be ‘Type 2’ to match overridden member ‘Member Name’

Reason for the Error

You’ll get this error in your C# code when you attempt to change the return type of the method when overriding.

For example, let’s try to compile the below C# code snippet.

using System;
namespace DeveloperPublishNamespace
{
    abstract public class BaseClass
    {
        virtual protected void Method1() 
        { 
        }
    }

    public class ChildClass : BaseClass
    {
        protected override int Method1()
        {
            return 0;
        }
    }
    class Program
    {
      
        static void Main(string[] args)
        {
            Console.WriteLine("No Error");
        }
    }
}

You’ll receive the error code CS0508 because the C# compiler has detected that you are changing the data type of the function “Method1” in the inherited class “ChildClass”.

Error CS0508 ‘ChildClass.Method1()’: return type must be ‘void’ to match overridden member ‘BaseClass.Method1()’ DeveloperPublish C:\Users\Senthil\source\repos\ConsoleApp4\ConsoleApp4\Program.cs 13 Active

C# Error CS0508 – 'Type 1': return type must be 'Type 2' to match overridden member 'Member Name'

Solution

You can fix this error in your C# program by making sure that both methods declare the same data type.

using System;
namespace DeveloperPublishNamespace
{
    abstract public class BaseClass
    {
        virtual protected void Method1() 
        { 
        }
    }

    public class ChildClass : BaseClass
    {
        protected override void Method1()
        {

        }
    }
    class Program
    {
      
        static void Main(string[] args)
        {
            Console.WriteLine("No Error");
        }
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...