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
{
}
}