Skip to content

NotNullIfNotNullOrEmpty and NotNullIfNotNullOrWhiteSpace attributes #108243

Answered by elgonzo
Foxtrek64 asked this question in Q&A
Discussion options

You must be logged in to vote

How would that work, considering that the compiler needs to know the actual string instance that would be passed to the method, something that would only happen during run-time and not during build/compile time?

Imagine this simple example:

public record Foo(string Bar);

string json = File.ReadAllText(pathToSomeJsonFile); 
//
// file might contain the json: { "Bar": "        " }
// or the file might contain any other json like { "Bar": "Snafu" } for example
//
Foo f = JsonSerializer.Deserialize<Foo>(json);
string? result = CreateSaferFileName(f.Bar);
Console.WriteLine(result.Length);

What is the compiler supposed to do here given your hypothetical NotNullIfNotNullOrWhiteSpaceAttribute?

A…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Foxtrek64
Comment options

Answer selected by Foxtrek64
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