Reputation: 53
In the below, C# is confident that 'property' will never be null, but I KNOW that it can be, because the external library is not produced with C#8/nullable types:
#nullable enable
SomeExternalClass obj = GetSomeExternalObjectFromAnOldAPI();
SomeExternalProperty property = obj.SomeProperty;
DoStuff(property); // C# is confident that property is not null, here
Here is a screenshot of the condition:
Doing the following doesn't provide a null warning either. C# still confidently assumes the external API is perfectly non-nullable:
#nullable enable
SomeExternalClass obj = GetSomeExternalObjectFromAnOldAPI();
SomeExternalProperty? property = obj.SomeProperty;
DoStuff(property); // C# is still confident that property is not null, here
Is there a way that I can force C# to acknowledge that a variable may be null, even if it is supposedly confident it won't be? The opposite of the ! symbol. 'Trust me, this garbage can be null..'
RESOLVED. ACCEPTED ANSWER:
#nullable enable
SomeExternalClass obj = GetSomeExternalObjectFromAnOldAPI();
SomeExternalProperty? property = obj.SomeProperty ?? null;
DoStuff(property); // C# is now warning about possible null
Upvotes: 5
Views: 815
Reputation: 4983
You can write a method ‘void MaybeNull([System.Diagnostics.CodeAnalysis.MaybeNull] T t)’ and use it.
Upvotes: 0
Reputation: 90
Try:
ElementId? viewTemplateId = (revitView.ViewTemplateId ?? someNullTypeOfYourChoosing);
Alternatively, allow the View
and revitView.ViewTemplateId
structs to be nullable/return nullable types.
Upvotes: 1