C# Error CS0127 – Since ‘function’ returns void, a return keyword must not be followed by an object expression

C# Compiler Error

CS0127 – Since ‘function’ returns void, a return keyword must not be followed by an object expression

Reason for the Error

You will receive this error when you have a method in C# with void return type and you are returning a value.

For example, try compiling the below code snippet.

namespace DeveloperPublishNamespace
{
    public class DeveloperPublish
    {
        public static void GetData()
        {
            return 0;
        }
        public static void Main()
        { 
        }
    }
}

You will receive this C# compiler error CS0127 because the method GetData which has the void return type is explicitly returning the value 0 inside the function.

Error CS0127 Since ‘DeveloperPublish.GetData()’ returns void, a return keyword must not be followed by an object expression ConsoleApp1 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.cs 7 Active

The error message might slightly look different but with the same error code when you are running a different version of .NET framework (for example Mono)

Main.cs(7,13): error CS0127: `DeveloperPublishNamespace.DeveloperPublish.GetData()’: A return keyword must not be followed by any expression when method returns void

Solution

To fix the CS0127 error, ensure that the method that has the void return type doesn’t return any value.

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...