78

Here's the scenario...

if (entry.Properties["something"].Value != null)
  attribs.something = entry.Properties["something"].Value.ToString();

While effective and working correctly, this looks ugly to me. If I don't check for a null before performing the ToString() then it throws an exception if the property was null. Is there a better way to handle this scenario?

Much appreciated!

6
  • So, what should the output be if the value is null? Feb 15, 2009 at 5:36
  • It would use the default value assigned to attribs.something
    – Dscoduc
    Feb 15, 2009 at 5:36
  • @dscoduc I'm looking for your HTA jQuery info from 2009. Is that still around? Your blog and site seem to be offline.
    – yzorg
    Jul 8, 2012 at 6:07
  • see also: stackoverflow.com/questions/24318654
    – dreftymac
    Jun 20, 2014 at 1:40
  • 2
    My question was from 2009 and the one you referenced is from 2010... so the other is a duplicate of mine, no?
    – Dscoduc
    Aug 6, 2016 at 3:34

12 Answers 12

129

Update 8 years later (wow!) to cover c# 6's null-conditional operator:

var value = maybeNull?.ToString() ?? String.Empty;

Other approaches:

object defaultValue = "default";
attribs.something = (entry.Properties["something"].Value ?? defaultValue).ToString()

I've also used this, which isn't terribly clever but convenient:

public static string ToSafeString(this object obj)
{
    return (obj ?? string.Empty).ToString();
}
4
  • 1
    Do you know off hand if the "default" could be replaced with string.Empty?
    – Dscoduc
    Feb 15, 2009 at 5:45
  • +1 and Answer: Just tested it and worked perfectly... Thank you!
    – Dscoduc
    Feb 15, 2009 at 5:53
  • Note that if the method making the call runs more than once and attribs is reused then you may be overwriting valid data gotten on 1 call with 'default' on a subsequent call.
    – xcud
    Feb 15, 2009 at 6:20
  • @xcud: True. In that case, he should use the following code: attribs.something = (entry.Properties["something"].Value ?? (objcet)attribs.something).ToString(); Feb 15, 2009 at 14:42
42

If you are targeting the .NET Framework 3.5, the most elegant solution would be an extension method in my opinion.

public static class ObjectExtensions
{
    public static string NullSafeToString(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
}

Then to use:

attribs.something = entry.Properties["something"].Value.NullSafeToString();
1
  • Beautiful. I'm just facing a conversion from 1.1 to 4.0, and in 1.1, null.ToString() actually returned "", so I got a couple of thousand occurrences to check for null-safety now. If I get this to work, this will make the transition so much smoother!
    – Nicolas78
    Nov 13, 2010 at 18:06
39
Convert.ToString(entry.Properties["something"].Value);
2
  • 40-Love - no, this returns null not an empty string if value is null. Feb 5, 2015 at 12:36
  • @ChrisPeacock no, check the documentation: the returned value of Convert.ToString(object value) is "The String representation of the value of 'value', or String.Empty if value is a null". A quick check in an actual program confirms this. Apr 11, 2018 at 8:04
3

Adding an empty string to an object is a common idiom that lets you do null-safe ToString conversion, like this:

attribs.something = ""+entry.Properties["something"].Value;

When entry.Properties["something"].Value is null, this quietly returns an empty string.

Edit: Starting with C# 6 you can use ?. operator to avoid null checking in an even simpler way:

attribs.something = entry.Properties["something"].Value?.ToString();
//                                                     ^^
2
  • this is more terse than the weird Convert.ToString call. Nov 24, 2015 at 15:40
  • @thepaulpage There's an even better way in C# 6. Nov 24, 2015 at 15:46
2

Can you not do:

attribs.something = entry.Properties["something"].Value as string;
4
  • No, you can't; if it's 'null' you'll get a null reference error. Sep 7, 2010 at 19:29
  • 1
    that works since it returns null string if value is null, and it does not throw exception.
    – live-love
    May 11, 2011 at 16:23
  • 2
    This does not work for value types. 'string str = myFloat as string;' fails. You will get the following compiler error Cannot convert type 'float' to 'string' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
    – CleanCoder
    Jan 13, 2012 at 23:12
  • 1
    Nooooo, if the type is not string will return null always!!! this is casting and not conversion! and won't work form value types!
    – Saw
    Nov 27, 2012 at 9:39
2
attribs.something = String.Format("{0}", entry.Properties["something"].Value);

Not sure about performance though...

2

In C# 6.0 you can do it in a very elegant way:

attribs.something = entry.Properties["something"].Value?.ToString();

And here is an article about new null-conditional operator.

1

As a variation to RexM's answer:

attribs.something = (entry.Properties["something"].Value ?? attribs.something).ToString()

The only downside would be that the attribs.something would be assigned a value (itself, in this example) even if entry.Properties["something"].Value was null - which could be expensive if the .something property did some other processing and/or this line executes a lot (like in a loop).

0
1

To do precisely what you're trying to do a helper method can always be used:

CopyIfNotNull(entry.Properties["something"].Value, out attribs.something);

void CopyIfNotNull(string src, out string dest)
{
  if(src != null)
    dest = src;
}
2
  • Don't you have to specify "out" in the second argument of the CopyIfNotNull?
    – Dscoduc
    Feb 15, 2009 at 5:54
  • yup. I realized that after I posted it.
    – Mike Hall
    Feb 15, 2009 at 21:27
1

Is it somehow possible to do something like Dale Ragan's answer above, but overriding ToString() instead of creating a new NullSafeToString() method? I'd like this (or returning "null") to be the default behaviour. The compiler (Visual C# 2010 Express) doesn't complain when I add the following method to public static class ObjectExtensions, but the method doesn't get called...

public static String ToString(this Object obj)
{
    if (obj == null)
    {
        return "null";
    }
    else
    {
        return obj.GetType().Name;
    }
}
1
  • 2
    Sure, since instance methods have higher priority than extension methods
    – codymanix
    Jun 20, 2011 at 15:19
1
attribs.something  = string.Format("{0}",entry.Properties["something"].Value)
0

How about using an auxiliary method like this:

attribs.something = getString(
    entry.Properties["something"].Value, 
    attribs.something);

static String getString(
    Object obj,
    String defaultString)
{
    if (obj == null) return defaultString;
    return obj.ToString();
}

Alternatively, you could use the ?? operator:

attribs.something = 
    (entry.Properties["something"].Value ?? attribs.something).ToString();

(note the redundant ToString() call when the value is null)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.