you can write
Dim displayName As String = "FirstName"
Dim myName As String = IIf((displayName = "FirstName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Abhishek"
myName = IIf((displayName = "SurName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Tiwari"
Please note that IIf is just a function which takes first input as an expression, evaluate it and return second input (if expression is evaluated to true) or return third input (if expression is evaluated to false).
There is a gotcha in using IIf function, it works little bit differently than ternary operator in C#. It basically evaluates both input (irrespective of expression evaluating to true or false). In Other languages, expression will be evaluated first and then based on the result other inputs will be evaluated.
for e.g.
Dim dict As New Dictionary(Of String, String)
Dim d = IIf(dict.ContainsKey("A"), dict("A"), Nothing)
will result in "KeyNotFound" exception although someone will assume that it should return Nothing without throwing exception.
Fortunately VB.Net 9 provides conditional operator (If) to be used as ternary operator too and it works exactly the same way the ternary operator works in C# or other language.
Dim dict As New Dictionary(Of String, String)
Dim d = If(dict.ContainsKey("A"), dict("A"), Nothing)
Note that I have used "If" instead of function "IIf" and later one will execute successfully and return Nothing without throwing any exception.
This blog gives very important info about .Net Thanks for sharing
ReplyDeleteDot Net Online Course
Your work is very good and I appreciate you and hopping for some more informative posts
ReplyDeleteDot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery