Share This!

Tuesday, December 3, 2013

Conditional Output with the ? Operator in C#

I needed to ensure that column data was trimmed to the correct lengths in a SQL insert.  Normally I would expect that this code...

string toobig="This string is exactly 37 characters.";
string nottoobig = "13 characters";


//attempt to trim both to 20

string s;
s = toobig.Substring(0, 20);
Console.WriteLine(s);

s = nottoobig.Substring(0, 20);
Console.WriteLine(s);

 ...would do the trick.

 Sadly, if you use substring with a length greater than your string, you don't get the whole string as you might expect, you get this.

System.ArgumentOutOfRangeException was unhandled
  Message=Index and length must refer to a location within the string.
Parameter name: length
  Source=mscorlib
  ParamName=length
So we need a way to trim a string only if it's needed, i.e. a conditional trim.  Normally this is written like this:

if (nottoobig.Length > 20) { s = nottoobig.Substring(0, 20); } else { s = nottoobig; };
This works, and so does this...

s = nottoobig.Substring(0, Math.Min(20, nottoobig.Length)); where we substring to the min of the actual length and the desired length.

But there is also this:

s = nottoobig.Length > 20 ? nottoobig.Substring(0, 20) : nottoobig; This works just like excel iif():
condition ? first_expression : second_expression;
Condition must be true or false. If true, the first_expression is used, if false, the second_expression is.


 

So I have written a clip() function that acts the way I expected substring() to:

        static void Main(string[] args)
        {
            string toobig = "This string is exactly 37 characters.";
            string nottoobig = "13 characters";
           
            //attempt to trim both to 20
            string s;
            s = clip(toobig,20);
            Console.WriteLine(s);

            s = clip(nottoobig, 20);
            Console.WriteLine(s);
        }

        private static string clip(string s, int max)
        {
            if (max < 0) max = 0;
            return s.Length > max ? s.Substring(0, max) : s;
        }



...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *