views:

206

answers:

5

I have a property declared as follows:

public decimal? MyProperty { get; set; }

I am needing to pass this value to another method as a string and so the only way I see to do so is as follows:

MyProperty == null ? null : MyProperty.ToString()

This looks very messy when you have a number of similar properties being passed into a method.

Does anyone know if there is a better and more concise way of writing this?

Oh, and if anyone can think of a more appropriate title to this question please feel free to change it...

+1  A: 

You could use HasValue instead of the comparison:

MyProperty.HasValue ? MyProperty.Value.ToString() : null;
Paul
should be MyProperty.Value.ToString()
ArsenMkrt
Sorry, have edited
Paul
+15  A: 

You can use the Nullable<T>.ToString() override ...

var s = MyProperty.ToString(); // returns "" if MyProperty is null
JP Alioto
Wow, really? Have learnt something new. I would never have tried that, thinking it would throw a null pointer exception
Paul
Wow! I had no idea .ToString still worked for a nullable value that was null. That's awesome!
mezoid
...But it sounds like the author wanted to have NULL if the value is NULL!!??
Dmytrii Nagirniak
@Dmitriy: null == "" for strings in .NET
Cameron MacFarland
@Cameron, I believe it (null != "") in .NET. Check it in your code.That is why we got string.IsNullOrEmpty method in .NET 2.0.
Dmytrii Nagirniak
+1  A: 

Make string get properties on the class containing the property and it won't be messy wen you need to get the string version.

    public decimal? MyProperty { get; set; }

    public string MyPropertyString
    {
        get
        {
            return MyProperty.HasValue ? MyProperty.Value.ToString() : null;
        }
    }
Jason w
+1  A: 

You could declare an extension method on Decimal.

public static string Str(this decimal? value)
{
    return value == null ? null : MyProperty.ToString()
}

You then call it like this:

MyProperty.Str()
Robert Harvey
No. Should be on decimal**?** (Nullable)
Dmytrii Nagirniak
+1  A: 

If it is ok to have zero istead of null then:

(MyProperty ?? 0).ToString()

Otherwise add extension method:

public static string AsString(this decimal? val)
{
    return val == null ? null : val.Value.ToString();
}

// Use:
MyProperty.AsString() // This will NEVER cause NullReferenceException
Dmytrii Nagirniak