C
C#12mo ago
corteZz-1

❔ What's the reason for the warning?

I don't understand why this warning create, because I created check with if
10 Replies
TheRanger
TheRanger12mo ago
you can add ! after [0] to silence the warning well i think is not null instead of != would silence the warning
Angius
Angius12mo ago
Or
if (products[0] is {} p)
{
val = p.Name;
}
if (products[0] is {} p)
{
val = p.Name;
}
corteZz-1
corteZz-112mo ago
okey. thanks
Jimmacle
Jimmacle12mo ago
why do you have Product?[] instead of Product[]? does that method return a collection that might have null elements? that's why the warning is there in the first place, you're telling the compiler that you expect some elements might be null
corteZz-1
corteZz-112mo ago
Well, the ?. operator indicates that the type can accept null. Because of this, the compiler will generate warnings everywhere to prompt null checks. I actually implemented the null check, but the warning didn't go away.
Jimmacle
Jimmacle12mo ago
right, so the root question is does GetProducts give you a collection that can have null elements? why would it do that?
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
corteZz-1
corteZz-112mo ago
I know, my question, okey I will show you two code, what is difference? why does one of them have a "warning" and the other one doesn't? 1) first one:
namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
Product?[] products = Product.GetProducts();
Product? p = products[0];
string val;
if (p != null)
{
val = p.Name;
}
else
{
val = "No value";
}
return View(new string[] { val });
}
}
}
namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
Product?[] products = Product.GetProducts();
Product? p = products[0];
string val;
if (p != null)
{
val = p.Name;
}
else
{
val = "No value";
}
return View(new string[] { val });
}
}
}
2) another one:
namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
Product?[] products = Product.GetProducts();

string val;
if (products[0] != null)
{
val = products[0].Name;
}
else
{
val = "No value";
}
return View(new string[] { val });
}
}
}

namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
Product?[] products = Product.GetProducts();

string val;
if (products[0] != null)
{
val = products[0].Name;
}
else
{
val = "No value";
}
return View(new string[] { val });
}
}
}

Second has warning
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.