-
Hi all, Hopefully opening this in the right repo. I was working on some code with file paths and writing a helper function which accepts a file name and performs some cleanup (including stripping characters contained within One of the first guards in the code is to look to see if the provided file name is null or white space, and if so, return I can annotate the function with Would a theoretical Example of use // "Safer" is used here because this function does not guarantee safety
// for any file system.
[return: NotNullIfNotNullOrWhiteSpace(nameof(fileName))]
public static string? CreateSaferFileName(string? fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return null;
}
// Method impl
return fileName;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 All the compiler knows is that the type of Checking the content of a string instance can only be a run-time check for any string instances not known during compile time. It can't possibly be a compile-time check, hence why a code-analysis attribute like |
Beta Was this translation helpful? Give feedback.
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:
What is the compiler supposed to do here given your hypothetical
NotNullIfNotNullOrWhiteSpaceAttribute
?A…