Oct 30, 2011

Ternary operator in C # and IIf in VB.NET. They are not equal.


A fairly widespread confusion out there is thinking that Visual Basic IIf function corresponds to the ternary operator in C #. Nothing is further from reality, then we will see an example that will show the subtle but important difference between the two ...
The following C # code works perfectly (or almost), in the example we try to assign a nullable date type variable input text using the ternary operator :
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main (string [] args)
{
DateTime? date = null;

Console. WriteLine ("Put the date (dd / mm / yyyy):");
string input = Console. ReadLine ();

date = (String. IsNullOrEmpty (input)?
null: (DateTime?) Convert. ToDateTime (input));

Console. WriteLine (fecha.ToString ());
Console. WriteLine ("Press [S] to repertoire");
repeat string = Console. ReadLine ();
if (repeat == "S")
Main (args);

}
}
}
The program runs without problems (provided you enter an expression valid date!). However, if you do the same with VB.NET, using the IIf function we get an error at runtime:
 Sub Main ()

Dim time As DateTime? = Nothing
Console. WriteLine ("Put the date (dd / mm / yyyy):")
Dim input As String = Console. ReadLine

date = IIf (String. IsNullOrEmpty (input), Nothing, Convert. ToDateTime (input))

Console. WriteLine (fecha.ToString)
Console. ReadLine ()
Console. WriteLine ("Press S for repertoire")
Dim As String = Console again. ReadLine
If (repeat = "S") Then
Main ()
End If
End Sub

The exception we get is the following:
String Was Not Recognized as a valid DateTime.
x10sctmp0
The reason is very basic mistake is that the ternary operator is an operator ...!, And IIf function is a function...! Surprise !!!!. That is, while the ternary operator is a symbol that the compiler performs the function invoked at runtime when invoked ... and evaluates all of its parameters, so that conversion to date - Convert.ToDateTime (input) - is performed regardless of the value of the variable (and is empty if it does not contain a valid expression for conversion to date, so that at runtime produces a FormatException.
In short, very careful with using the IIf function ...

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes