0

My question is that why we need to check for null error in string[]. isn't it that string type can accept the null value by default? so why we should check that if string [] contains null by using Null conditional operator token(?).

for Example look at this method:

it's from the book C# and NetFramework 4.6

static void TesterMethod(string[] args)
{
  // We should check for null before accessing the array data!
Console.WriteLine($"You sent me {args?.Length} arguments.");
}

I mean if we can assign null to a string why we should check for the null error? why should this throw an error?

Console.WriteLine($"You sent me {args.Length} arguments.");
Mohsen
  • 167
  • 2
  • 14

2 Answers2

7

If args is null, calling a property on it (Length) will cause a NullReferenceException. You have to make sure args is not null before calling.

And args is an array of type string, not a string itself.

so why we should check that if string [] contains null by using Null conditional operator token(?)

It doesn't contain null, it is null. The conditional operator checks the array, not the contents of the array.

Community
  • 1
  • 1
Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294
0

Well, when you try to access or change a String with the value null, it can throw an exception.

Recently I was working on a Contact List application for school, and I encountered an error from a null value in my String array while trying to print through a For Each loop (I was using VB.NET, but the concept is the same in most of the NetFramework). As the loop went, it would search through an array to print the information for the selected Contact. However, the loop would stop if it reached a null value, terminating the application.

So, it's somewhat situational. If you want to make sure that an accident can't stop your program prematurely, it's best to try for a null exception just in case. But if your program can run as expected, and if a user cannot break it by accident, then you may not need to check.

Lupus Nox
  • 142
  • 8