C# Teaser - The Tricky Ternary Teaser?
Today we came across a little quirk that is worth sharing. Big thanks to Bob Flanders and Jeff Schoolcraft for help in figuring out the quirk.
The Rules:
- Prize (a Thycotic keyring light) to be mailed to the first comment with the correct answer(s) on this blog post with valid contact information.
- My definition of the problem is the correct one. :) Other answers might be right but won't win the prize.
- I will post the answer within a few days.
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Teasers
{
public class TernaryTeaser
{
private object GetValue(Control o)
{
return (o is TextBox && ((TextBox)o).Text.Trim() != "") ?
((TextBox) o).Text : System.DBNull.Value;
}
}
}
- What is the problem and what is the easiest way to fix it?
- Why do ternaries work this way - is there something at the compiler or IL level?
The first person to successfully answer part (1) gets a hearty pat on the back, the first person to explain part (2) gets a Thycotic keyring light.
UPDATE: Thanks to Kirk and Joseph for spotting the logic error - not what I was looking for, just my silly oversight (where's a test when you need one!) - I have updated the code to make more sense.
Winner: Jonathan de Halleux
Answer & Discussion (click and drag your mouse to see the answer)
| Answer: The simplest fix I was looking for is casting the System.DBNull.Value to an object: return (o is TextBox && ((TextBox)o).Text.Trim() != "") ? |
For the answer to part (2), see Jonathan de Halleux's awesome detailed comment below.