SlideShare a Scribd company logo
Of complicacy of programming, or won't
C# save us?
Author: Evgeniy Ryzhkov

Date: 26.10.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)

    {

        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++?

    1. Interaction with different API's, as, for instance, in case of interacting with Visual Studio API
       described above.
    2. Interaction with programs written in other languages. For instance, the __time64_t type
       certainly came from a C++-application.
    3. Interaction with the operating system. Far not always we can match a nice and correct C#-code
       with the harsh reality represented by Windows.
    4. 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:

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

More Related Content

PDF
Source code of WPF samples by Microsoft was checked
PDF
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
PDF
Checking Clang 11 with PVS-Studio
PDF
A fresh eye on Oracle VM VirtualBox
PDF
Errors that static code analysis does not find because it is not used
PDF
Checking Notepad++: five years later
PDF
Documenting Bugs in Doxygen
PDF
Checking VirtualDub
Source code of WPF samples by Microsoft was checked
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Checking Clang 11 with PVS-Studio
A fresh eye on Oracle VM VirtualBox
Errors that static code analysis does not find because it is not used
Checking Notepad++: five years later
Documenting Bugs in Doxygen
Checking VirtualDub

What's hot (20)

PDF
Date Processing Attracts Bugs or 77 Defects in Qt 6
PDF
The First C# Project Analyzed
PDF
PVS-Studio: analyzing ReactOS's code
PDF
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
PDF
CppCat Static Analyzer Review
PDF
PVS-Studio advertisement - static analysis of C/C++ code
PDF
Checking OpenCV with PVS-Studio
PDF
PVS-Studio: analyzing ReactOS's code
PDF
Firefox Easily Analyzed by PVS-Studio Standalone
PDF
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
PPT
Javascript quiz. Questions to ask when recruiting developers.
PDF
Linux version of PVS-Studio couldn't help checking CodeLite
PDF
PVS-Studio vs Chromium
PDF
PVS-Studio vs Chromium
PDF
Analyzing the Blender project with PVS-Studio
PDF
A Slipshod Check of the Visual C++ 2013 Library (update 3)
PDF
Picking Mushrooms after Cppcheck
PDF
PVS-Studio vs Chromium - Continuation
PDF
Critical errors in CryEngine V code
PPTX
Switch case and looping new
Date Processing Attracts Bugs or 77 Defects in Qt 6
The First C# Project Analyzed
PVS-Studio: analyzing ReactOS's code
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
CppCat Static Analyzer Review
PVS-Studio advertisement - static analysis of C/C++ code
Checking OpenCV with PVS-Studio
PVS-Studio: analyzing ReactOS's code
Firefox Easily Analyzed by PVS-Studio Standalone
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Javascript quiz. Questions to ask when recruiting developers.
Linux version of PVS-Studio couldn't help checking CodeLite
PVS-Studio vs Chromium
PVS-Studio vs Chromium
Analyzing the Blender project with PVS-Studio
A Slipshod Check of the Visual C++ 2013 Library (update 3)
Picking Mushrooms after Cppcheck
PVS-Studio vs Chromium - Continuation
Critical errors in CryEngine V code
Switch case and looping new
Ad

Viewers also liked (20)

PPTX
Static analysis of C++ source code
PDF
Lesson 10. Pattern 2. Functions with variable number of arguments
PDF
Safety of 64-bit code
PDF
Lesson 14. Pattern 6. Changing an array's type
PDF
Development of resource-intensive applications in Visual C++
PDF
Lesson 1. What 64-bit systems are
PDF
Static code analysis and the new language standard C++0x
PDF
The reasons why 64-bit programs require more stack memory
PDF
Explanations to the article on Copy-Paste
PDF
Lesson 9. Pattern 1. Magic numbers
PDF
Lesson 26. Optimization of 64-bit programs
PDF
Detection of vulnerabilities in programs with the help of code analyzers
PDF
An eternal question of timing
PDF
Analysis of the Ultimate Toolbox project
PDF
Introduction into 64 bits for the beginners or where's again the 64-bit world?
PDF
The forgotten problems of 64-bit programs development
PDF
Comparing capabilities of PVS-Studio and Visual Studio 2010 in detecting defe...
PDF
Optimization of 64-bit programs
PDF
How we test the code analyzer
PDF
The essence of the VivaCore code analysis library
Static analysis of C++ source code
Lesson 10. Pattern 2. Functions with variable number of arguments
Safety of 64-bit code
Lesson 14. Pattern 6. Changing an array's type
Development of resource-intensive applications in Visual C++
Lesson 1. What 64-bit systems are
Static code analysis and the new language standard C++0x
The reasons why 64-bit programs require more stack memory
Explanations to the article on Copy-Paste
Lesson 9. Pattern 1. Magic numbers
Lesson 26. Optimization of 64-bit programs
Detection of vulnerabilities in programs with the help of code analyzers
An eternal question of timing
Analysis of the Ultimate Toolbox project
Introduction into 64 bits for the beginners or where's again the 64-bit world?
The forgotten problems of 64-bit programs development
Comparing capabilities of PVS-Studio and Visual Studio 2010 in detecting defe...
Optimization of 64-bit programs
How we test the code analyzer
The essence of the VivaCore code analysis library
Ad

Similar to Of complicacy of programming, or won't C# save us? (20)

PDF
Thinking In Swift
PDF
Looking for Bugs in MonoDevelop
PDF
Robots in Swift
PDF
Still Comparing "this" Pointer to Null?
PDF
Sony C#/.NET component set analysis
PDF
Headache from using mathematical software
PDF
Zero, one, two, Freddy's coming for you
PDF
Checking the Source Code of FlashDevelop with PVS-Studio
PDF
Boo Manifesto
PDF
Top 10 bugs in C++ open source projects, checked in 2016
PDF
Cpp17 and Beyond
PDF
Rechecking SharpDevelop: Any New Bugs?
PDF
Intel IPP Samples for Windows - error correction
PDF
Re-checking the ReactOS project - a large report
PDF
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
PDF
Consequences of using the Copy-Paste method in C++ programming and how to dea...
PDF
How to avoid bugs using modern C++
PDF
Intel IPP Samples for Windows - error correction
PDF
Intel IPP Samples for Windows - error correction
PDF
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Thinking In Swift
Looking for Bugs in MonoDevelop
Robots in Swift
Still Comparing "this" Pointer to Null?
Sony C#/.NET component set analysis
Headache from using mathematical software
Zero, one, two, Freddy's coming for you
Checking the Source Code of FlashDevelop with PVS-Studio
Boo Manifesto
Top 10 bugs in C++ open source projects, checked in 2016
Cpp17 and Beyond
Rechecking SharpDevelop: Any New Bugs?
Intel IPP Samples for Windows - error correction
Re-checking the ReactOS project - a large report
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Consequences of using the Copy-Paste method in C++ programming and how to dea...
How to avoid bugs using modern C++
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PDF
KodekX | Application Modernization Development
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
Reach Out and Touch Someone: Haptics and Empathic Computing
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectral efficient network and resource selection model in 5G networks
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
KodekX | Application Modernization Development
Machine learning based COVID-19 study performance prediction
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
A Presentation on Artificial Intelligence
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

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

  • 1. Of complicacy of programming, or won't C# save us? Author: Evgeniy Ryzhkov Date: 26.10.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()); }
  • 2. 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) {
  • 3. 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 {
  • 4. 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;
  • 5. 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;
  • 6. 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++)
  • 7. { 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++? 1. Interaction with different API's, as, for instance, in case of interacting with Visual Studio API described above. 2. Interaction with programs written in other languages. For instance, the __time64_t type certainly came from a C++-application. 3. Interaction with the operating system. Far not always we can match a nice and correct C#-code with the harsh reality represented by Windows. 4. 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: 1. Comments are cut out; code is abridged to the minimum amount necessary for the article.
  • 8. 2. Yes, the authors of the code are not good at writing in C# but C# doesn't get more magical because of that.