Of complicacy of programming, or won't C# save us?

26.10.2010 Evgeniy Ryzhkov

Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".

Further are several fragments in C# taken from the module of integrating the PVS-Studio static code analyzer into a popular environment Microsoft Visual Studio. I want to show by the example of these fragments that it is quite not easier to write in C#, for instance, than in C++.

Simple combobox

So, the first code fragment is responsible for processing selection of one of the three lines in a COMMON combobox on the toolbar (Figure 1).

Figure 1 - Common three-line combobox

Figure 1 - Common three-line combobox

To process such a little thing, you need to write the following code. Unfortunately, we had to change formatting and remove comments. So, please forgive me for this horrible text.

private void OnMenuMyDropDownCombo(object sender, EventArgs e)
{
  if (e == EventArgs.Empty)
  {
    throw (new ArgumentException());
  }

  OleMenuCmdEventArgs eventArgs = e as OleMenuCmdEventArgs;

  if (eventArgs != null)
  {
    string newChoice = eventArgs.InValue as string;
    IntPtr vOut = eventArgs.OutValue;

    if (vOut != IntPtr.Zero && newChoice != null)
    {
      throw (new ArgumentException());
    }
    else if (vOut != IntPtr.Zero)
    {
      Marshal.GetNativeVariantForObject(
        this.currentDropDownComboChoice, vOut);
    }

    else if (newChoice != null)
    {
      bool validInput = false;
      int indexInput = -1;
      for (indexInput = 0;
           indexInput < dropDownComboChoices.Length;
           indexInput++)
      {
        if (String.Compare(
            dropDownComboChoices[indexInput], newChoice,
            true) == 0)
        {
          validInput = true;
          break;
        }
      }

      if (validInput)
      {
        this.currentDropDownComboChoice =
            dropDownComboChoices[indexInput];
        if (currentDropDownComboChoice ==
            Resources.Viva64)
          UseViva64Analysis(null, null);
        else if (currentDropDownComboChoice ==
                 Resources.GeneralAnalysis)
          UseGeneralAnalysis(null, null);
        else if (currentDropDownComboChoice ==
                 Resources.VivaMP)
          UseVivaMPAnalysis(null, null);
        else
        {
          throw (new ArgumentException());
        }
      }
      else
      {
        throw (new ArgumentException());
      }
    }
    else
    {
      throw (new ArgumentException());
    }
  }
  else
  {
    throw (new ArgumentException());
  }
}

You will ask what for there are IntPtr.Zero and Marshal.GetNativeVariantForObject(). Well, it must be so... It is not so simple to implement processing of a simple combobox.

Moreover, this code is not enough. There is the OnMenuMyDropDownComboGetList() function nearby which is of almost the same size.

C# turned out to be in no way better than any other language here. Well, of course, it is cool that it encapsulated OLE and marshalling from me; it would be much worse in C. But still everything looks in reality different than presented in books and by evangelists. Where is the promised simplicity? All I wanted to do is just to work with a drop-down combobox.

Navigation through code in Visual Studio

When you click an error message in Visual Studio, the program executes a code similar to the following one to open the file and pass on to the line containing the error.

public void OpenDocumentAndNavigateTo(string path, int line, 
  int column)
{
IVsUIShellOpenDocument openDoc =
              Package.GetGlobalService(
              typeof(IVsUIShellOpenDocument))
              as IVsUIShellOpenDocument;
     if (openDoc == null)
       return;
     IVsWindowFrame frame;
     Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp;
     IVsUIHierarchy hier;
     uint itemid;
     Guid logicalView = VSConstants.LOGVIEWID_Code;
     if (ErrorHandler.Failed(
        openDoc.OpenDocumentViaProject(path, ref logicalView, 
          out sp, out hier, out itemid, out frame))
            || frame == null)
              return;
     object docData;
     frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, 
       out docData);

     VsTextBuffer buffer = docData as VsTextBuffer;
     if (buffer == null)
     {
          IVsTextBufferProvider bufferProvider = 
              docData as IVsTextBufferProvider;
          if (bufferProvider != null)
          {
            IVsTextLines lines;
            ErrorHandler.ThrowOnFailure(
              bufferProvider.GetTextBuffer(out lines));
            buffer = lines as VsTextBuffer;
            if (buffer == null)
              return;
          }
     }
  IVsTextManager mgr = 
    Package.GetGlobalService(typeof(VsTextManagerClass))
    as IVsTextManager;
  if (mgr == null)
    return;
  mgr.NavigateToLineAndColumn(
     buffer, ref logicalView, line, column, line, column);
}

What the hell!.. How terribly... Just a mess of magic spells... Again, this code written in C# did not make life of its developer any easier. Who can say that it would look better in the XYZ language? The language here is "perpendicular" to the task being solved and has almost no influence on the solution.

Processing date

Well, at least processing of dates in C# must be good! For they made so many various convenient formats!.. So I believed until an external application returned time in the format __time64_t and C# code required using the DateTime class.

Of course it's easy to convert __time64_t into DataTime, you just need to write a function similar to this one:

public static DateTime Time_T2DateTime(long time_t)
{
  //116444736000000000 - this is year 1600
  long win32FileTime = 10000000 * time_t + 116444736000000000;
  return DateTime.FromFileTime(win32FileTime);
}

C# didn't show any better results here as well... Maybe I failed to find a conversion function. But, hell, was it really so hard to make the necessary constructor for DateTime? Why, when it comes to interacting with the environment, do we have to do everything "with our hands", in the old fashion?

Search of all the projects of one solution

It may be necessary to search for all the projects included into a Visual Studio solution for some tasks.

Instead of using a simple and nice foreach, we must write the following code:

Solution2 solution = PVSStudio.DTE.Solution as Solution2;
SolutionBuild2 solutionBuild = 
    (SolutionBuild2)solution.SolutionBuild;
SolutionContexts projectContexts = 
    solutionBuild.ActiveConfiguration.SolutionContexts;

int prjCount = projectContexts.Count;
for (int i = 1; i <= prjCount; i++)
{
    SolutionContext projectContext = null;
    try
    {
        projectContext = projectContexts.Item(i);
    }
    catch (Exception)
    {
        // try/catch block is a workaround. 
        // It's needed for correct working on solution 
        // with unloaded projects.
        continue;
    }
...

First, it appears that foreach is unavailable for this class. Well, let it be, we still remember how to use for. Second, if you address an element which is included into the set but its state is "not very correct", an exception is thrown. As a result, the code gets much more complicated. So again the code in C# in no way differs from code in any other language.

Conclusions

By writing this post I wanted to show that far not always code in C# (or any other language) is simpler than code in C/C++. That is why you shouldn't believe blindly that "everything must be rewritten in C#". However, I do not think that "C# is junk" because it really makes life easier in many aspects.

What are the reasons why code fragments mentioned in this post look as complicated as fragments in C++?

  • Interaction with different API's, as, for instance, in case of interacting with Visual Studio API described above.
  • Interaction with programs written in other languages. For instance, the __time64_t type certainly came from a C++-application.
  • Interaction with the operating system. Far not always we can match a nice and correct C#-code with the harsh reality represented by Windows.
  • Imperfection of data processing algorithms. If you work with strings, you cannot get rid of "+1" in your code whatever language you use.

Justification for code used in samples:

  • Comments are cut out; code is abridged to the minimum amount necessary for the article.
  • Yes, the authors of the code are not good at writing in C# but C# doesn't get more magical because of that.