String.Join - different behavior for the parameter and direct value

Viewed 118

I run code bellow, result1 is equal "" but string.Join(",", null) throw an exception

string str = null;
var result1 = string.Join(",", str);
var result2 = string.Join(",", null);

Also it doesn't work for this code(throw an exception)

.ForMember(dst => dst.Ids, opt => opt.MapFrom(string.Join(",", src.Ids)))

But works for this:

.ForMember(dst => dst.Ids, opt => opt.MapFrom(src => src.Ids == null ? null : string.Join(",", src.Ids)))

How explain this behaviour?

3 Answers

Both use the same overload of string.Join - which is the one that takes in a string as a separator and string[] as a value.
More accurately - params string[] value - and that is the key point of the observed difference behavior.

The first line of code - string.Join(",", str); where str is a null reference of a string, actually gets resolved as string.Join("," new string[] {null}).

The second line, however, gets resolved as string.Join("," null). - meaning the string array itself is null and therefor the exception is thrown.

update You get different results with automapper because the result of the following code

string str = null;
var result1 = string.Join(",", str);

is not null, it's an empty string.

The 2nd parameter for join takes in params string[] value. In your first case you are sending in an array of strings with 1 value (null). For the 2nd case you are sending in null as the string array.

First Try

string str = null;
var result1 = string.Join(",", str);

The code above transalted into

string text = null;
string[] obj = new string[1];
string text2 = string.Join(",", obj);

Second Try

And last line of code;

var result2 = string.Join(",", null);

translated into;

string.Join(",", (string[])null);

You can see yourself at https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTjTRUcADOgM4AuATugC86AHYBXADaSA3MgBuAQ0H8Aptym84wzJwB0AKQD2AS1HUARABprPAbTlIlK9Zpg72HQ6fPXbE6QcWdABfZBCgA==

P.S: sharplab is love =)

Related