The VB.NET Ternary Operator

I think the VB.NET Ternary Operator may be the last operator that I really miss in VB.NET from my curly brace language experience.  Although, I have to admit, I wouldn’t have missed it all that much if they never added it.  There just isn’t a whole lot of use for it.

However, the Ternary operator is a REALLY nice feature to have available to you when you do need it.  It’s another one of those language features that falls under, “Just because it is there doesn’t mean you have to use it.”

If you’ve ever run into a situation where you just need a simple evaluation and assign a variable based on it.  Like this:

        Dim s As String 
        If Session("mySessionVar") Is Nothing Then 
            s = String.Empty 
        Else 
            s = Session("mySessionVar").ToString() 
        End If 

you’ll appreciate the new Ternary operator which shrinks it to:

        Dim s As String 
        s = If(Session("mySessionVar") Is Nothing, _ 
               String.Empty, Session("mySessionVar").ToString)
Note that this NOT the same as
        Dim s As String 
        s = IIf(Session("mySessionVar") Is Nothing, _ 
               String.Empty, Session("mySessionVar").ToString)

Here’s the difference between the two.

IIf will always evaluate the second and third parameter regardless of if the first parameter evaluates to true or false.  This is because IIf is a function, not an operator.

If is an operator, and therefore only evaluates the second OR third parameter when they are the value that will ultimately be returned.  So, If() will run my code above without any errors while IIf will throw a null pointer exception when Session(“mySessionVar”) evaluates to nothing because it will try to apply ToString() to the object that is null.

Technorati Tags: ,

  

del.icio.us Tags: ,

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • Object Initialization in CSharp 3.0 and VB.NET 9Object Initialization in CSharp 3.0 and VB.NET 9 Yesterday we looked at the new var keyword in CSharp.  This makes CSharp variable declaration similar to VB.  After all, they've had the DIM keyword for years which essentially does the […]
  • Intellisense Everywhere in VB 9 (and a small bug)Intellisense Everywhere in VB 9 (and a small bug) One of the features the CSharp guys have had for quite a while is Intellisense everywhere.  Want to create a private variable?  Just start typing private and hit the tab key as soon as the […]
  • Anonymous TypesAnonymous Types So, let's get to work looking at anonymous types in .NET.As you know, last week we looked at object initialization.  Object initialization allows us to instantiate an object and […]
  • CSharp adds the var keyword!CSharp adds the var keyword! There have been several new features added to the CSharp language that will significantly reduce the amount of code that ends up in our source files.  It will not significantly reduce the […]
  • Simple Properties in C# 3.5Simple Properties in C# 3.5 It's such a little thing.  But, how much of our CSharp code looks something like this: private string _propertyName;public string PropertyName { get { […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

  • Tern Aryfa IL

    horrible example that leads developers to write ugly unmaintainable code.

    I like the first example

    • Dave

      I’m not sure what you are trying to express. What are you referring to as a “horrible example that leads developers to write ugly unmaintainable code”? The statement, itself is an opinion. What makes the code ugly? What makes it unmaintainable?

  • Tern Aryfa IL

    your second example takes a fraction of a second longer to read/understand than the first. I get where you’re going with it but the example was a poor one.

    someone scanning your example quickly would read a line that had if( _ on one line.

    and stuff on a second line.

    Because the second and third parameters in your ternary operation are not simple, there is a level of effort that a person has to apply; they have to (1)interpret that it’s a ternary operation and (2)read into the line to find the else condition.

    For that example, using the traditional If/Else pattern is more legible. A simpler example such as the following would be a more legible application of the operation.

    strLightColor = if(started, “green”, “red”)

    Side note to your “I think this may be the last operator that I really miss in VB from my curly brace language experience. ” comment.

    Most “curly brace” languages have this available:

    strLightColor = started ? “green” : “red”;

    • Dave

      If I understand you correctly, your chief complaint is that it is on two lines instead of one. If I were writing code for a program instead of writing code for a blog post, I would have placed it all on one line. Unfortunately, putting it all on one line would have made it too wide to display correctly.

      In defense of the example itself, I would be more likely to use this syntax to check for nothing prior to using the value as I have done in this example then I would be to return one of two values as you do with your example. Why? Because it violates the “if there are N+1 of something today, you should make sure the code supports N+2 in the future” If there is two of something, at some point in the future, there is likely to be three of something. The code should be written to support that. The best syntax for your example would be a select/case construct, although I’ll admit I rarely see that done.

      As for “harder to understand” I’ve heard this argument made over and over again when a new feature is added to a language that reduces the amount of code we have to write. It’s never been a very powerful argument for me. To me it essentially argues that because most people aren’t familiar with this syntax, we should continue to write more code. If they were familiar with the syntax, it wouldn’t be a struggle for them any more than a typical if/then construct.

      It is a similar argument to saying we shouldn’t use words that are more specific just because most people would need to get out a dictionary to find out what the word means.

      By doing this, it will always be a new construct (or in the case of language, be an unknown word) so no one will learn it and it will never become mainstream. By introducing less familiar syntax into our code where it makes sense, we help educate the junior programmers who will have to struggle a bit to understand the code and actually raise the syntax past the level of obscurity it might otherwise maintain.

      I appreciate your chiming in with your opinion and supporting it. If my arguments haven’t convinced you, we’ll have to agree to disagree. At the end of the day what matters most is that the code does what it should. Second to that is that is can be maintained. It sounds to me like you would at least agree that my code could be maintained, as I will agree yours could. Degrees of difficulty and opinions about what makes code easy or hard are just that. Opinions.

  • Tern Aryfa IL

    good points but i think you’re off the mark on my position. It’s not so much the two lines as it is the type of parameters you’re using for the second and third positions.

    I guess it comes down to this:

    “black”,”white”

    vs

    String.Empty, Session(“mySessionVar”).ToString()

    when the parameters get as complicated as your example array index lookup + function call, it makes it harder to distinguish the two parts of the statement without having to do more than a quick scan with your eyes.

    It has nothing to do with being familiar with the ternary pattern you’re using for the conditional and everything to do with the amount of time it takes to pick out what the “else statement” is.

    Hope this better clarifies my position on this :p