When to use Null Forgiving (!) vs Non-Nullable casts
In this example, n needs to be cast from int? to int
My question is why null forgiving (!) syntax does not seem to work (new int[n!];] and where null forgiving syntax would actually be applicable.
int? n = null;
string input;
if (int.TryParse(input,out _))
{
n = int.Parse(input);
}
int[] arr = new int[(int)n];n will never be nullint.TryParse(), something made explicitly for the purpose of avoiding throwing format exceptions... to throw a format exception.TryParse()int.TryParse() lets you avoid exceptions


while(input==null){
if (int.TryParse(input,out _))
{
n = int.Parse(input);
}
} if (int.Parse(input) < 0)
{
Console.Write("Number must be a positive integer. ");
continue;
}
else if (!int.TryParse(input, out _))
{
throw new FormatException();
}
else if (int.TryParse(input, out _))
{
n = int.Parse(input);
} if (int.Parse(input) < 0)
{
Console.Write("Number must be a positive integer. ");
continue;
}
else if (!int.TryParse(input, out _))
{
throw new FormatException();
}
else if (int.TryParse(input, out n))
{ }nnullint.TryParse()int.TryParse().TryParse()if (int.TryParse(input,out _))
{
n = int.Parse(input);
}if (int.TryParse(input, out n))
{
}int? n = null;
if (int.TryParse(input,out _))
{
n = int.Parse(input);
}
var arr = new int[n];if (int.TryParse(input, out var n))
{
var arr = new int[n];
}if (int.TryParse(input, out var num))
{
if (num < 0)
{
// ...
}
if (num % 2 == 0)
{
// ...
}
var arr = new int[num];
// etc
}