Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing a compilation null reference warning for a particular case. #44184

Open
phoeniceus opened this issue Jan 8, 2025 · 1 comment
Open

Comments

@phoeniceus
Copy link

phoeniceus commented Jan 8, 2025

Type of issue

Missing information

Description

When you call a class constructor and it throws an exception, it still calls the finalizer. This code throws a null reference exception, however there is no null reference warning when the code compiled. Can we get that warning added or an explanantion why it is not there?

  public class Foo
  {
    private string _name;
    private Bar _bar;

    public Foo(string name)
    {
      ArgumentNullException.ThrowIfNullOrEmpty(name);
      _name = name;
      _bar = new Bar();
    }

    ~Foo()
    {
      Dispose();
    }

    public void Dispose()
    {
      _bar.Dispose(); // This is the line throwing the null reference exception.
        GC.SuppressFinalize(this);
    }
  }

  public class Bar: IDisposable
  {
    public void Dispose() { }
  }

  public void Main()
  {
     var foo = new Foo(string.Empty);
  }

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/nullable-warnings

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/language-reference/compiler-messages/nullable-warnings.md

Document Version Independent Id

df58b52a-2532-8241-72cd-f40e9096037d

Article author

@BillWagner

Metadata

  • ID: 812f0144-80de-6b49-dded-97eeb7bc373d
  • Service: dotnet-csharp
  • Sub-service: errors-warnings

Related Issues

@BillWagner
Copy link
Member

Hi @phoeniceus

Yes, this is a one of a number of holes in the nullability static analysis. In general, full static analysis on fields is going to have some holes. The static analysis can't predict what order public methods are accessed. And, as your example points out, static analysis can't determine if a method (like a constructor) completes without a runtime exception being thrown.

This article should reference the section on known pitfalls in the nullable reference types. In addition, that section should discuss other pitfalls, as shown in this article.

@BillWagner BillWagner removed the ⌚ Not Triaged Not triaged label Jan 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants