Search code examples
c#code-analysisc#-8.0

Compiler Error With "DoesNotReturn" Attribute


I have implemented some static throw helper methods in a net-standard 2.1 (C# 8.0) project.

[DoesNotReturn]
public static void InvalidOperation(String message, String caller, String path, Int32 line)
{
  throw new InvalidOperationException($"{message}\n{caller}|{path}|{line}");
}

I want to use them in a NET 5.0 project like:

public static BitmapSource GetBitmapSource(String uri)
{
    if (Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out Uri? _uri))
    {
        return new BitmapImage(_uri);
    }

    Throw.InvalidOperation( $"Invalid uri {uri}.");
}

But the the compiler still returns the error CS0161: "Not all code paths return a value"


Solution

  • Write the exceptional path first:

    public static BitmapSource GetBitmapSource(String uri)
    {
        if (!Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out Uri? _uri))
        {
            Throw.InvalidOperation( $"Invalid uri {uri}.");
        }
    
        return new BitmapImage(_uri);
    }
    

    Now, as far as the compiler is concerned, the method returns.


    Another thing to consider is to have the helper method return the exception, instead of throwing it. The method that calls it can throw it. That way the compiler would know that it throws. Which also means you don't get the helper method in the stack trace of the exception.


    By the way, for reference of people finding this, I believe the helper method in the question is intended to use these: Reserved attributes: Determine caller information.