Choosing a return value for a method in C#

Tom Meier 80 Reputation points
2024-04-23T16:42:27.2233333+00:00

Hi there! I have a method, but I'm not sure what I want the return value to be yet. Is there a best practice for using a temporary return value so that I won't get a compile error and can run my application until I decide what I want for the return value? Thank you!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,274 questions
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 11,005 Reputation points MVP
    2024-04-23T17:04:58.69+00:00

    Yep, you can use a placeholder or temporary return value to avoid compile errors while you're still deciding on the final return value for your C# method. One common approach is to return a default or sentinel value that clearly indicates that the method is incomplete or the return value is temporary.

    Here's an example using null as a placeholder return value:

    public string MyMethod()
    {
        // Placeholder return value
        return null;
    }
    
    

    Using null as the placeholder allows your method to compile and run without errors, but it's important to remember to update the return value to the correct type and value once you've decided on the final return value.

    Alternatively, you can use a specific value that wouldn't normally occur in the context of your method's logic. For example, if your method typically returns a string, you might use an empty string or a special string like "TODO" as a placeholder:

    public string MyMethod()
    {
        // Placeholder return value
        return "TODO";
    }
    
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    0 comments No comments

0 additional answers

Sort by: Most helpful