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

Request our prices
New License
License Renewal
--Select currency--
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

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


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)
        this.currentDropDownComboChoice, vOut);

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

      if (validInput)
        this.currentDropDownComboChoice =
        if (currentDropDownComboChoice ==
          UseViva64Analysis(null, null);
        else if (currentDropDownComboChoice ==
          UseGeneralAnalysis(null, null);
        else if (currentDropDownComboChoice ==
          UseVivaMPAnalysis(null, null);
          throw (new ArgumentException());
        throw (new ArgumentException());
      throw (new ArgumentException());
    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 =
              as IVsUIShellOpenDocument;
     if (openDoc == null)
     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)
     object docData;
       out docData);

     VsTextBuffer buffer = docData as VsTextBuffer;
     if (buffer == null)
          IVsTextBufferProvider bufferProvider = 
              docData as IVsTextBufferProvider;
          if (bufferProvider != null)
            IVsTextLines lines;
              bufferProvider.GetTextBuffer(out lines));
            buffer = lines as VsTextBuffer;
            if (buffer == null)
  IVsTextManager mgr = 
    as IVsTextManager;
  if (mgr == null)
     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 = 
SolutionContexts projectContexts = 

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

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.


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
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: Nov 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…
The way static analyzers fight against false positives, and why they do it

Date: Mar 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…
PVS-Studio for Java

Date: Jan 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…
The Evil within the Comparison Functions

Date: May 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…
The Ultimate Question of Programming, Refactoring, and Everything

Date: Apr 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…
Appreciate Static Code Analysis!

Date: Oct 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…
Static analysis as part of the development process in Unreal Engine

Date: Jun 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…
Free PVS-Studio for those who develops open source projects

Date: Dec 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…
PVS-Studio ROI

Date: Jan 30 2019

Author: Andrey Karpov

Occasionally, we're asked a question, what monetary value the company will receive from using PVS-Studio. We decided to draw up a response in the form of an article and provide tables, which will sho…

Comments (0)

Next comments
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 →