E
E
embiid2022-02-18 21:13:48
C++ / C#
embiid, 2022-02-18 21:13:48

How to check for null?

Data comes to the model, but there is data that is null;
How can I check for null in a line, and if it's null - insert some line?

For example:

new DataModel()
{
   Id = entity.Id,
   Name = к примеру, приходит. Я хочу сделать проверку на null, и если тут null вписать string - "Name"
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-02-18
@embiid

In general, xs, how did you not think of the simplest thing - through if:

string name;
if(entity.Name == null)
{
  name = "Name";
}
else
{
  name = entity.Name;
}
DataModel dataModel = new DataModel()
{
  Id = entity.Id,
  Name = name
};
// ...

But in general there is this syntax:
new DataModel
{
  Id = entity.Id,
  Name = entity?.Name ?? "Name"
}

If you still need to handle emptiness, then the shortest option will be like freeExec
Here are links to the documentation:
string.IsNullOrEmpty: https://docs.microsoft.com/ru-ru/dotnet/api/system...
About ??: https ://docs.microsoft.com/en-us/dotnet/csharp/lan...
About?.: https://docs.microsoft.com/en-us/dotnet/csharp/lan...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question