C# Error CS1520 – Method must have a return type

C# Error

CS1520 – Method must have a return type

Reason for the Error & Solution

Method must have a return type

A method that is declared in a class, struct, or interface must have an explicit return type. In the following example, the IntToString method has a return value of :

class Test  
{  
    string IntToString(int i)  
    {  
        return i.ToString();  
    }  
}  

The following sample generates CS1520:

public class x  
{  
   // Method declaration missing a return type before the name of MyMethod
   // Note: the method is empty for the purposes of this example so as to not add confusion.
   MyMethod() { }
}  

And can be fixed by adding a return type to the method, such as adding void in the example below:

public class x  
{  
   // MyMethod no longer throws an error, because it has a return type -- "void" in this case.
   void MyMethod() { }
}  

Alternatively, this error might be encountered when the case of a constructor’s name differs from that of the class or struct declaration, as in the following sample. Because the name is not exactly the same as the class name, the compiler interprets it as a regular method, not a constructor, and produces the error:

public class Class1  
{  
   // Constructor should be called Class1, not class1  
   public class1()   // CS1520  
   {  
   }  
}  

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...