C
C#2y ago
devhl

✅ NotNullWhen not working as expected

This must just be a Roslyn bug...right?
using System.Diagnostics.CodeAnalysis;

namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string userInput = "foo";

bool isFormatted = TryFormat(userInput, out string? formattedUserInput);

if (isFormatted)
Console.WriteLine(formattedUserInput.ToString()); // 'formattedUserInput' may be null here
}

public static bool TryFormat(string userInput, [NotNullWhen(true)] out string? output)
{
output = userInput;

return true;
}
}
}
using System.Diagnostics.CodeAnalysis;

namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string userInput = "foo";

bool isFormatted = TryFormat(userInput, out string? formattedUserInput);

if (isFormatted)
Console.WriteLine(formattedUserInput.ToString()); // 'formattedUserInput' may be null here
}

public static bool TryFormat(string userInput, [NotNullWhen(true)] out string? output)
{
output = userInput;

return true;
}
}
}
2 Replies
phaseshift
phaseshift2y ago
remove 'isformatted' intermediate variable if (TryFormat(...)) {...
devhl
devhlOP2y ago
ohhh...it works in another case because I return if false. I guess that works but this doesn't. Thanks
Want results from more Discord servers?
Add your server