N
N
Nikita072021-11-11 08:31:37
C++ / C#
Nikita07, 2021-11-11 08:31:37

What does this notation mean in C#?

Hello everyone, please help me with the following code:

private static string GetUserAgent(this HttpRequestMessage request)
            => request.Headers?.UserAgent?.ToString() ?? string.Empty;


What do the question marks mean in this case?
That the given expression can be null or something else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Voland69, 2021-11-11
@Nikita07

Such a Headers?.UserAgent entry is a Null Propagation - if Headers == null the expression will return null (without the ? it would be NRE)
value ?? string.Empty is comparing value with null - if value != null then return value, otherwise return string.Empty

V
Vladimir Korotenko, 2021-11-11
@firedragon

In addition to the above

///
// Метод возвращает UserAgent из запроса или пустую строку. Производится проверка на пустое значение Headers и UserAgent
///
private static string GetUserAgent(this HttpRequestMessage request)
            => request.Headers?.UserAgent?.ToString() ?? string.Empty;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question