C# ?(question) Operator, How I ? Thee ….
Posted: October 6, 2010 Filed under: C# | Tags: ?, C#, C# question operator Leave a comment »Alright Dudes and Dudettes ….
One of the best things that I enjoy everyday while coding (sometimes work is so boring you have to appreciate the smaller things in life….? ) is the “?” operator. Most awesomely for “if else” short cut …
n00bin it up example:
bool isSomething = true;
string words = "";
if (isSomething)
{
words = "It is something";
}
else
{
words = "Sorry, this is nothing.";
}
With a little sprinkle of demon juice:
bool isSomething = true; string words = (isSomething) ? "It is something" : "Sorry, this is nothing.";
Same block of code two lines. Some people will throw their arms up like one of these:

and Say, “Oh it is embedding logic that’s hard to find ………. “
Anyway, Almost got side tracked there. I love it, makes the code a lot cleaner. It is especially fun checking for nulls before assigning values:
float iamfloating = float.Parse((reader["iamfloat"] == null ? "0" : reader["iamfloat"].ToString())); string message = objectthatshasmessage != null ? objectthatshasmessage.Message : "No Message";
Now there is this really evil thing you can use ? for. You can use it to make primitive types nullable
bool? isSomething = null;. WTF? I know. I have committed sin and have used this in projects. Mostly working with databases. Simply because you can make most fields nulllable in your tables. However, I coming to the conclusion that this is wrong.
Why? Well for example, bit (or bool in c#) it suppose to represent 2 states, off/on, false/true, 0/1. You get it right. If I make it nullable isn’t that essential assigning a third state to bit/bool, defeating the purpose of bool!!!!!!! Same goes with other primitive types, think about it…. Love ya!
Fritz