Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write this line of C# code in C#3.0?

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

like image 377
mezoid Avatar asked Aug 07 '09 04:08

mezoid


People also ask

Can C be written on one line?

Being a bit naive, standard C requires an empty newline at the end of your source code, so 1-line programs that actually do something are impossible.

Is there an end of line character in C?

In programming languages, such as C, Java, and Perl, the newline character is represented as a '\n' which is an escape sequence.

Can you break lines in C?

There is a character for that. It's called "newline". You can't put it directly in the string because that would create a new line in the source code, but inside quotes in C you can produce it with \n . Alternatively, instead of printf you could use puts , which prints a new line after the string.


2 Answers

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

var s = MyProperty.ToString(); // returns "" if MyProperty is null
like image 190
JP Alioto Avatar answered Nov 08 '22 19:11

JP Alioto


You could use HasValue instead of the comparison:

MyProperty.HasValue ? MyProperty.Value.ToString() : null;
like image 21
Paul Avatar answered Nov 08 '22 18:11

Paul