Skip to content

Analyze nullable return value statically? #46496

Answered by PathogenDavid
Cyl18 asked this question in Q&A
Discussion options

You must be logged in to vote

I believe what you're looking for is the nullable analysis attributes.

Specifically, NotNullIfNotNull: (Full example on SharpLab here)

[return: NotNullIfNotNull("obj")]
public static object? ToObject<T>(this T obj) => obj;

As an aside:

var obj1Result = obj1.ToObject(); // should be object

With var this will always be object?, but the compiler will know it is not null. (Whether a particular variable is known to be null or able to be null are separate concepts. var is always nullable, but may or may not be known to be null.)

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@Cyl18
Comment options

@PathogenDavid
Comment options

Answer selected by Cyl18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants