Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 893
Basil Kosovan Avatar asked Dec 31 '22 21:12

Basil Kosovan


1 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.

like image 94
Zohar Peled Avatar answered Jan 04 '23 23:01

Zohar Peled