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() != "") ? ((TextBox) o).Text : (object) System.DBNull.Value; |
For a full explanation of the ternary/conditional operator, read the docs.
For the answer to part (2), see Jonathan de Halleux's awesome detailed comment below.