You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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);
}
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.
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?
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
Related Issues
The text was updated successfully, but these errors were encountered: