How to tips and tricks for Microsoft Visual Studio .net

Tuesday, September 25, 2012

IIf in c#


Visual Basic and c# are very similar. That's my opinion, but in some small cases there is no similarity.


The VB IIf function is one example of which there is nothing that looks even slightly similar in c#.
The equivalent in c# is…

a == "1" ? true : false;

How to use this is pretty simple…
    bool ReturnedValue = a == "1" ? true : false;
or
    int ReturnedValue = a == "1" ? 5 : 10;
or
    string ReturnedValue = a == "canine" ? "dog" : "cat";

However you decide to use it, it looks a bit strange to a veteran VB user.
To make it more VB friendly I have these methods that look and function like the VB IIf function…


    private object IIf(bool Expression, object TruePart, object FalsePart)
    {
      object ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private string IIf(bool Expression, string TruePart, string FalsePart)
    {
      string ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private bool IIf(bool Expression, bool TruePart, bool FalsePart)
    {
      bool ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

    private int IIf(bool Expression, int TruePart, int FalsePart)
    {
      int ReturnValue = Expression == true ? TruePart : FalsePart;

      return ReturnValue;
    }

Use them like this…
    string ReturnedValue = IIf(aa == "canine", "dog", "cat");

Happy coding

4 comments:

  1. This post is getting loads of interest, but no comments?

    ReplyDelete
  2. thanks for providing this code its really use full for Dot net users who is expert in VB6

    ReplyDelete
    Replies
    1. You are welcome... If there is anything else you would like to see, please let me know so I can see if I can show how it's done.

      Delete