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!

Rex M
  • 142,167
  • 33
  • 283
  • 313
Dscoduc
  • 7,714
  • 10
  • 42
  • 48

12 Answers12

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();
}
Jim Buck
  • 2,383
  • 23
  • 42
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • 1
    Do you know off hand if the "default" could be replaced with string.Empty? – Dscoduc Feb 15 '09 at 05:45
  • +1 and Answer: Just tested it and worked perfectly... Thank you! – Dscoduc Feb 15 '09 at 05: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 '09 at 06:20
  • @xcud: True. In that case, he should use the following code: attribs.something = (entry.Properties["something"].Value ?? (objcet)attribs.something).ToString(); – configurator Feb 15 '09 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();
Dale Ragan
  • 18,202
  • 3
  • 54
  • 70
  • 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 '10 at 18:06
  • Wow did this ever save me a lot of time! Thanks! – Brad Aug 25 '11 at 17:02
39
Convert.ToString(entry.Properties["something"].Value);
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
Vahid
  • 391
  • 3
  • 2
  • 40-Love - no, this returns null not an empty string if value is null. – Chris Peacock Feb 05 '15 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. – Rob Gilliam Apr 11 '18 at 08: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();
//                                                     ^^
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
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.

ZuoLi
  • 383
  • 2
  • 14
2
attribs.something = String.Format("{0}", entry.Properties["something"].Value);

Not sure about performance though...

2

Can you not do:

attribs.something = entry.Properties["something"].Value as string;
NotDan
  • 31,709
  • 36
  • 116
  • 156
  • No, you can't; if it's 'null' you'll get a null reference error. – George Stocker Sep 07 '10 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 '11 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 '12 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 '12 at 09:39
1
attribs.something  = string.Format("{0}",entry.Properties["something"].Value)
sra
  • 23,820
  • 7
  • 55
  • 89
aljj
  • 106
  • 5
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;
    }
}
Community
  • 1
  • 1
Dave the Rave
  • 181
  • 1
  • 3
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).

PhilChuang
  • 2,556
  • 1
  • 23
  • 29
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;
}
Mike Hall
  • 1,151
  • 2
  • 10
  • 24
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)

Zach Scrivena
  • 29,073
  • 11
  • 63
  • 73