Quick Tip: Comparing a .NET string to multiple values

The Problem

Do you ever wish you could use the SQL IN operator in your C# code to make your conditional blocks more concise and your code easier to read?

Perhaps it’s just my persnickety nature, but I believe that line-wrapped conditional expressions like this are a code smell.

if (animal.Equals("Cow") ||
   animal.Equals("Horse") ||
   animal.Equals("Hen"))
{
   Console.WriteLine("We must be on the farm.");
}

This would be so much cleaner…

if (animal.CompareMultiple("Cow","Horse","Hen")
{
   Console.WriteLine("We must be on the farm.");
}

The Code

With a simple extension class you can upgrade your string classes to do this very thing.

Step 1: Create an extension class as demonstrated here.

C#

namespace extenders.strings
{
  public static class StringExtender {

    public static bool CompareMultiple(this string data, StringComparison compareType, params string[] compareValues) {
      foreach (string s in compareValues) {
        if (data.Equals(s, compareType)) {
          return true;
        }
      }
      return false;
   }
  }
}

VB.NET

Imports System.Runtime.CompilerServices

Namespace Extenders.Strings

  Public Module StringExtender

    <Extension()> _
    Public Function CompareMultiple(ByVal this As String, compareType As StringComparison, ParamArray compareValues As String()) As Boolean

       Dim s As String

       For Each s In compareValues
         If (this.Equals(s, compareType)) Then
            Return True
         End If
       Next s

       Return False
    End Function

  End Module

End Namespace

Step 2: Add a reference to the extension namespace and use it.

C#

using extenders.strings;

namespace MyProgram
{
  static class program {
    static void Main() {

      string foodItem = "Bacon";

      if (foodItem.CompareMultiple(StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) {
         System.Console.WriteLine("Breakfast!");
      }
      else {
         System.Console.Write("Dinner");
      }

    }
  }
}

VB.NET

Imports StringExtenderExampleVB.Extenders.Strings

Module Program

  Sub Main()
    Dim foodItem As String = "Bacon"

    If (foodItem.CompareMultiple(System.StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) Then
      System.Console.WriteLine("Breakfast!")
    Else
      System.Console.Write("Dinner")
    End If

    System.Console.ReadLine()
  End Sub

End Module

Why you need to know C++

I saw an interesting question on stack overflow wherein the questioner asks why everyone keeps telling him that he has to learn C++ to be a professional developer. Although it is true that most of these discussions are just launching pads for religious wars and I’m not alone in  my assertion that your language of choice is largely irrelevant , I do agree with the perhaps controversial notion that every working programmer should be at least conversant, if not fluent in C++.

Let me be entirely clear about this. I am not saying that C++ has to be your primary language or that you need to be a C++ guru to work in this business. However, it behooves you to be able to competently read and write basic code in this language.  That is, you should at the very least be able to implement the FizzBuzz program and the cliched example of a Zoo program to demonstrate polymorphism without lifting someone else’s code.

Before you dismiss me as a platform snob, consider the following six reasons that you need to know C++

1.      You should learn C++ for the same reasons that people study dead languages like Latin. The syntax and other memes in higher level languages were inspired by or directly stolen from C++. This is blatantly obvious for Java, C#, and JavaScript. Learning C++ is a quick way to grok the syntax for a several languages at once and better understand their origins.

2.      Understanding the details that are abstracted away from you in other languages (pointers, basic data structures, garbage collection, etc.) will ultimately make you more adept at solving problems when the abstractions innevitably leak or the stalwart underlying technology doesn’t live up to its stalwartitude.

Consider the real world example of anti-lock breaks, which allow you to maintain control of a car during an emergency stop. ABS has a completely idiot proof interface –Jam foot on pedal– that works just whether or not you understand that it will electronically pump the breaks to prevent the wheels from locking. However, during an attempt to thwart an impending moose collision it is certainly comforting to understand why the car is stopping in jerks instead of a smooth motion despite steady pressure on the pedal.

Also, this knowledge might have prevented my wife from listening to a shady mechanic who conned her into thinking that she had to pay his exorbitant rate to fix her ABS system since the truck wasn’t safe to drive without it to another mechanic for a second opinion.

3.      Like it or not, C++ is the lingua franca of programming. Some would argue for Java, or even JavaScript, which may appear true in much the same way that the ocean appears to contain water because of all the wet swimmers who frequent it. It’s best just to accept this, but if you need reinforcement all you need to know is that Software Jesus (Joel Spolskyagrees with me * on this, case closed.  

4.     Programmers and programming books that need to address programmers who speak an unknown or different language often use C++ for the same reasons noted in point #3. Learning this language will open access to more learning material and help you communicate with the programming community more easily.

5.     One day you are going to need sully yourself and interface directly to a C API from the lofty perch of your high level language. In my experience a lot of tool developers avoid the hassle of maintaining separate COM, .NET, and Java API’s by just providing a a C API that will appease all the peasants who are not as privileged as they to “work in a real language.”

6.     C++ on your resume can often lead to Salary++. I’ve found this is true even if the job doesn’t require any C++ programming.  It is just respected as a more hardcore language and the credibility rubs off on those who use it. That credibility makes you more valuable.

 * Update: As noted by a commenter (BTW: Thanks for the correction), Joel did make a definite distinction that new programmers should be learning C and not necessarily C++.  Apologies for misstating his position. While it is true that for just many of the points I made, you could easily substitute C for C++ and get the same bang for your buck, I contend that C++ is a stronger foundational language for the points detailed in 1,3, and 4.  Using a language that can’t talk about objects (C) to communicate with other programmers in an overwhelmingly OOP world isn’t gonna cut it.

A Manager’s Retrospective on the C# versus VB.NET decision

There is no shortage of discussion or flame wars weighing the relative merits of the various Microsoft .NET programming languages, nor is there an outcry for another opinion on the subject. This article will instead discuss the process of making a sound business decision on a controversial issue without inciting mutiny among the developers. More importantly, I’ll revisit some of the key considerations in that decision through the razor sharp focus of hindsight. It is my hope that my experiences from the trenches will provide guidance to software development managers who have not yet made the jump to .NET, are bootstrapping a new shop, or are considering a switch from another platform.

It’s been just over six years since I managed the transition of my development team to Microsoft’s .NET platform and made the call, for better or worse, to standardize on VB.NET. As a developer myself, I was keenly aware of the how the programming language of a software development shop defines its culture and similarly shapes the professional identity of many programmers. The polemic among developers created a real risk of breaking down the team dynamic through second-guessing and deflated morale regardless of my choice. As is the case with implementing any politically sensitive change, the prudent course of action was to aggressively seek buy-in by actively soliciting input of each team member, remaining visibly objective, and maximizing the transparency of the issues that factored into the final decision. Despite the lack of unanimity requiring over 30% of the team to acquiesce on this hot-button standardization issue, the team dynamic remained strong after my final decision.

The Players

Although the list of languages that are currently supported on the .NET framework is more diverse than most would probably imagine, the options were far more limited back in 2003.

C#.NET: A hybrid of C and Java that attempted to lure defectors from the Java camp to the .NET platform. It also provides an easy transition for C++ refugees who are sick of the annoyances of manual memory management and having 9 incompatible ways to implement a simple string.

J#.NET: Most of the quirks of Java and none of the cross-platform support and about as useful as non-alcoholic beer. Enables developers to pretend they still hate Microsoft, but participate in their market share. Also allows Microsoft to pretend that C# wasn’t a blatant attempt to crush the upstart Java language that threatened to weaken their dominance of the OS market. The technology pundits have moved on to other issues enough for Microsoft to silently drop support for J# from Visual Studio.

VB.NET: The next generation of the popular Visual Basic language, all grown up and fully OOP capable. It is unfortunate that Microsoft didn’t take this opportunity to rename the language to remove the stigma associated with programmers using this language that only resembles its forebears in its verbosity. I assume they kept the name to provide an unambiguous upgrade path for the unwashed masses of VB6 programmers many of which ironically and belligerently dug in their heels and refused to upgrade.

C++.NET: For a while I assumed that I must have been missing something with respect to C++.NET. The juxtaposition of the venerable I’ll-roll-my-own-thank-you-very-much C++ and the don’t-worry-your-pretty-little-head-about-cleaning-up-that-memory .NET framework felt even more awkward than “Java.NET.” I took a course to absolve me of my silly notions, but only managed to reinforce them. C++.NET is neither fish nor fowl. It is like a halfway house for recovering masochist programmers who really want to like automated garbage collection, but want to take it one day at a time. Just one more hit of STL, I promise I’ll quit tomorrow! In one of the rare parallels with the VB camp, many of the Microsoft Visual C++ developers found little motivation to abandon Visual Studio 6.

The Contenders

Let’s face it. Aside from C#, VB.NET, and their ugly cousin C++.NET, none of the remaining .NET languages were used for much more than  Microsoft demos to prove that they wanted to support open standards. This was even truer back in 2003 when I was weighing the options. The team divided itself naturally into a C# and VB.NET camp and no one even hinted at seriously considering a third option.

The Process

It is extremely important when soliciting input from employees to be very clear about how the final decision is going to be made, especially when it is not the purely democratic process that they might otherwise assume. Recognizing this, I was careful to communicate that while everyone’s input was valued and would be carefully considered, I’d be making the final decision based on both the advice of the team and the interests of the business. I promised complete transparency on my decision and a chance to appeal it on factual, but not subjective grounds. As it happened, no such appeals were proffered. The C# proponents were slightly disappointed, but were also thankfully supportive the decision to go with VB.NET.

My solicitation for input included the following:

  • Provide as many supporting arguments for your preference as apply to our environment.
  • Arguments based on business objectives (reduced cost, greater efficiency) will be weighed more heavily.
  • Performance comparisons between the languages had been researched and dismissed already, don’t bother including them.
  • It is perfectly valid to support your preference in terms of your personal goals (money, prestige, taste, etc.).
  • Regardless of whether you can support your preference, please indicate it in your response. Morale impact is a key consideration.

Facts, Factors and Opinion

After compiling my own research, business case analysis, and the collective wisdom and opinion of my team, the following key themes emerged.

  • Functionality (TIE): Functional differences between the capabilities of these languages were primarily cosmetic/syntactic/irrelevant(Appleman/Atwood), MSDN.  There were a few IDE features that one language or the other had the edge on, but MS was already promising IDE parity in future releases.
  • Learning Curve (VB.NET): Because our previous standard was VBScript for ASP pages, and VB6 for the middle tier object layers, VB.NET seemed like the quickest path to productivity. I was particularly concerned about the impact of forcing the developers to make the jump to a completely different language at the same time they would be also required to get up to speed on the .NET framework and ASP.NET.
  • Existing Code (VB.NET): We were maintaining a significant amount of existing VB6 and VBScript code that would need to be ported to .net. Visual Studio provided tools to automate most of the conversion from to VB.NET, but considerable extra time would have been required to go to C#.
  • Product Road maps for .NET languages (VB.NET): An MSDN magazine article comparing the road maps for the two languages indicated that VB.NET was going to continue to be optimized for rapid application development while C# would follow the tradition of C++ and trend towards power-user features. The direction of VB.NET was more relevant to our development efforts which were mostly on CRUD type applications.
  • Developer Preferences (VB.NET): Despite the tendency of most to gravitate towards the familiar in platform wars, C# had a good showing. The balance was tipped by a few developers who had already started down the VB.NET track of their MCSD certifications. I hate to reinforce the stereotype, but it was interesting to note that the more senior developers were mostly in the C# camp.
  • Developer “Street Creds” (C#): Almost all of the developers subscribed at least weakly to the popular notion that C# experience would command a higher premium than VB.NET by riding the coattails of C++ as a more respected language. Whether justified or not, it appears that this rumor has become fact.
  • Product “Street Creds” (C#): There was also some concern that the “taint of VB” would hurt the perceived professionalism of our software among our customers. I have not yet seen evidence of this, however, we don’t advertise the language we use, and our customers don’t generally ask or care.
  • Recruiting (TIE C#): There was a lot of discussion that MS was strongly favoring C# as the language of choice for .NET and that most developers were following suit. I was somewhat concerned about the possibility of VB.NET becoming marginalized and creating recruiting hurdles. That is, if VB.NET became uncool, it might be difficult to get people to respond to our job postings even if we didn’t discriminate against people with only experience in other .NET languages. On the other hand, I reasoned that we might be able to avoid paying a “C# premium” that didn’t guarantee any associated additional value add over a competent VB.NET programmer. I think that predictions of VB.NET’s demise were very premature as it continues to have a solid following. However, in retrospect, I think I underestimated the impact of the decision on recruiting. I suspect that some of our recruiting difficulty (even with very competitive salaries) can be attributed to the fact that VB.NET developers readily apply to C# jobs, but the reverse is not as common.
  • Language Obsolescence (Non-factor): A small contingent was even predicting that Microsoft planned to phase out VB.NET in favor of C#. I just didn’t buy into this notion given my experience with how slowly Microsoft has retired product lines in the past. It took them 27 years, for example, to retire FoxPro after acquiring it, and salvaging it for parts to include in their competing database package, MS Access. So far it appears my skepticism was warranted.

Recommendations

As I have already mentioned, our team went with VB.NET. I still think it was probably the right decision given the skills of my existing team and our considerable investment in legacy code in VB based languages, despite the minor difficulties it has created for recruiting. Absent either of these preconditions, however, I definitely would suggest a preference for C# for any manager going through this decision today. That said, this article is no substitute for your own research. As is the case with any heated topic, there is an abundance of misinformation, some of which may even be repeated by members of your own team. One resource that I have come to trust over my years in this industry is Dan Appleman, who has published a highly regarded e-book, Visual Basic .NET or C#, Which to Choose? (VS2005 edition).

The lesson that can be drawn from my experience, however, is not so much about a preference of one language over the other, but instead the importance of involving the whole team in the change management process. This decision has major ramifications on their professional careers that extend beyond the walls of your organization and has the potential to create significant anxiety among them. Manage that anxiety by including them in the process, making it clear that their individual interests are being carefully considered, and the making the decision objectively and transparently as possible.

Links to the Fray