0

Why String.Trim() throws an exception on string.empty when it is used in a Razor view like this:

console.log('@Model.Test.FirstOrDefault().Trim()');

(the list is empty so i get string.empty) and then:

Server Error in '/' Application.
Object reference not set to an instance of an object.
(...)'
Line 326:            console.log('@Model.Test.FirstOrDefault().Trim()');
yennsarah
  • 5,467
  • 2
  • 27
  • 48
Carlos28
  • 2,381
  • 3
  • 21
  • 36

2 Answers2

6

If the list is empty as you say then you won't get a string.Empty but an null, as the default value of the first element of an empty list of strings is null and you can't call .Trim() on a null object.

If you are using C# 6 then you could do something like this:

console.log('@Model.Test.FirstOrDefault()?.Trim()');

Note the addition of a question mark before the .Trim(), that puts a null check in so that trim will only be called if the left side is not null.

Alternatively you could do:

console.log('@(Model.Test.FirstOrDefault() ?? string.Empty).Trim()');

Which is uses the null coalescing operator to explicitly replace the null with a string.Empty and is available in previous versions of C#

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
0

You probably have null somewhere. You can overcome it easily by using elvis operator in c#6:

console.log('@Model.Test?.FirstOrDefault()?.Trim()??"Null property"');
Tajkia Rahman Toma
  • 472
  • 1
  • 5
  • 16
Ashkan S
  • 10,464
  • 6
  • 51
  • 80
  • 1
    Do not overuse the ?. operator - It can lead to buggy code. Use it only where you know there will be a null value that you want to deal with in a specific way. – Colin Mackay Jul 20 '16 at 08:34
  • I don't think that is overusing ?. The line is clear. He wants to use the string value for something and the null value has to be checked. Elvis operator is there to skip to much unwanted code for null check when there is no need – Ashkan S Jul 20 '16 at 08:49
  • You know where the possible null is (after `.FirstOrDefault()`) The other places you've used it have not been identified as where the return value is a null or that it is useful that it is because you forced yourself into that corner - It it doesn't (or should never) return null you should not be checking for it as you'll hide bugs. Your answer and follow up comment demonstrate exactly why I thought this addition to the language was a bad idea. You are overusing it and you cannot see that you are. All you have done is recreate the old VB OnErrorContinue scenario. – Colin Mackay Jul 20 '16 at 08:57