To get a trial key
fill out the form below
Team License (standard version)
Enterprise License (extended version)
* By clicking this button you agree to our Privacy Policy statement

** This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

** This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
Of complicacy of programming, or won't …

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

Oct. 26, 2010

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).

0081_Programming_is_difficult/image1.png

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.

Popular related articles
PVS-Studio for Java

Date: 01.17.2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
Static analysis as part of the development process in Unreal Engine

Date: 06.27.2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
The way static analyzers fight against false positives, and why they do it

Date: 03.20.2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…
The Evil within the Comparison Functions

Date: 05.19.2017

Author: Andrey Karpov

Perhaps, readers remember my article titled "Last line effect". It describes a pattern I've once noticed: in most cases programmers make an error in the last line of similar text blocks. Now I want t…
Appreciate Static Code Analysis!

Date: 10.16.2017

Author: Andrey Karpov

I am really astonished by the capabilities of static code analysis even though I am one of the developers of PVS-Studio analyzer myself. The tool surprised me the other day as it turned out to be sma…
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: 11.21.2018

Author: Andrey Karpov

A brief description of technologies used in the PVS-Studio tool, which let us effectively detect a large number of error patterns and potential vulnerabilities. The article describes the implementati…
Free PVS-Studio for those who develops open source projects

Date: 12.22.2018

Author: Andrey Karpov

On the New 2019 year's eve, a PVS-Studio team decided to make a nice gift for all contributors of open-source projects hosted on GitHub, GitLab or Bitbucket. They are given free usage of PVS-Studio s…
The Ultimate Question of Programming, Refactoring, and Everything

Date: 04.14.2016

Author: Andrey Karpov

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The au…
Characteristics of PVS-Studio Analyzer by the Example of EFL Core Libraries, 10-15% of False Positives

Date: 07.31.2017

Author: Andrey Karpov

After I wrote quite a big article about the analysis of the Tizen OS code, I received a large number of questions concerning the percentage of false positives and the density of errors (how many erro…
How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers

Date: 10.22.2018

Author: Andrey Karpov

Just like other static analyzers, PVS-Studio often produces false positives. What you are about to read is a short story where I'll tell you how PVS-Studio proved, just one more time, to be more atte…

Comments (0)

Next comments

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept