CSHARP_CI Telegram 1520
❗️C# вопрос с собеседования: Middle–Senior level

Вопрос: почему возникает предупреждение о возможном null, если ProductStock здесь явно не равен null?

Код:

private static IEnumerable<Error> VerifyProductQuantities(
List<ProductStock> products,
Dictionary<string, Domain.Entities.ProductStock> stocks)
{
foreach (var product in products)
{
if (!stocks.TryGetValue(product.ProductName, out var stock))
{
yield return StockErrors.ProductNotFound(product.ProductName);
}

if (stock.AvailableQuantity < product.Quantity)
{
yield return StockErrors.InsufficientStocks(
product.ProductName, product.Quantity, stock.AvailableQuantity);
}
}
}


Компилятор выдет: «Dereference of a possibly null reference» для переменной stock.

Почему так происходит?
• Метод TryGetValue возвращает false, и тогда stock остаётся равным null.
• Даже если мы отфильтровали это через if (!TryGetValue(...)), компилятор не гарантирует, что в блоке после условия stock точно не null.
• В результате в строке if (stock.AvailableQuantity < product.Quantity) возникает предупреждение.

Как исправить?
1. Добавить continue после yield return внутри блока if (!TryGetValue(...)). Тогда компилятор поймёт, что кода после этой ветки для null не будет.
2. Либо использовать оператор !:
if (stock!.AvailableQuantity < product.Quantity) — но это безопасно только если мы уверены, что значение точно не null.
3. Более читаемый вариант — переписать логику так, чтобы работа с stock была строго в ветке, где оно гарантированно задано.

Вопрос для проверки понимания nullable reference types и поведения компилятора при анализе путей выполнения кода.



tgoop.com/csharp_ci/1520
Create:
Last Update:

❗️C# вопрос с собеседования: Middle–Senior level

Вопрос: почему возникает предупреждение о возможном null, если ProductStock здесь явно не равен null?

Код:


private static IEnumerable<Error> VerifyProductQuantities(
List<ProductStock> products,
Dictionary<string, Domain.Entities.ProductStock> stocks)
{
foreach (var product in products)
{
if (!stocks.TryGetValue(product.ProductName, out var stock))
{
yield return StockErrors.ProductNotFound(product.ProductName);
}

if (stock.AvailableQuantity < product.Quantity)
{
yield return StockErrors.InsufficientStocks(
product.ProductName, product.Quantity, stock.AvailableQuantity);
}
}
}


Компилятор выдет: «Dereference of a possibly null reference» для переменной stock.

Почему так происходит?
• Метод TryGetValue возвращает false, и тогда stock остаётся равным null.
• Даже если мы отфильтровали это через if (!TryGetValue(...)), компилятор не гарантирует, что в блоке после условия stock точно не null.
• В результате в строке if (stock.AvailableQuantity < product.Quantity) возникает предупреждение.

Как исправить?
1. Добавить continue после yield return внутри блока if (!TryGetValue(...)). Тогда компилятор поймёт, что кода после этой ветки для null не будет.
2. Либо использовать оператор !:
if (stock!.AvailableQuantity < product.Quantity) — но это безопасно только если мы уверены, что значение точно не null.
3. Более читаемый вариант — переписать логику так, чтобы работа с stock была строго в ветке, где оно гарантированно задано.

Вопрос для проверки понимания nullable reference types и поведения компилятора при анализе путей выполнения кода.

BY C# (C Sharp) programming




Share with your friend now:
tgoop.com/csharp_ci/1520

View MORE
Open in Telegram


Telegram News

Date: |

Ng Man-ho, a 27-year-old computer technician, was convicted last month of seven counts of incitement charges after he made use of the 100,000-member Chinese-language channel that he runs and manages to post "seditious messages," which had been shut down since August 2020. The court said the defendant had also incited people to commit public nuisance, with messages calling on them to take part in rallies and demonstrations including at Hong Kong International Airport, to block roads and to paralyse the public transportation system. Various forms of protest promoted on the messaging platform included general strikes, lunchtime protests and silent sit-ins. While some crypto traders move toward screaming as a coping mechanism, many mental health experts have argued that “scream therapy” is pseudoscience. Scientific research or no, it obviously feels good. To upload a logo, click the Menu icon and select “Manage Channel.” In a new window, hit the Camera icon. How to Create a Private or Public Channel on Telegram?
from us


Telegram C# (C Sharp) programming
FROM American