C# vs C++

[Update: Changed a misplaced "C#" to a "C++" in the tools section. Thanks, Nick]

At the class a took a while back, the instructor asked me to talk a little bit about the benefits of C++ vs the benefits of C#, since I had worked in C++, then in C#, and now in C++ again.

I talked for about 5 minutes on why C# was better, in the following themes. Note that I'm speaking about the whole programming environment, not just the language.

Automatic memory management

There are several facets of this. When I read or write C++ code,  I keep part of my attention on the algorithmic aspects of the code, and another part on the memory aspects of the code. In C#, I usually don't have to worry about the memory aspects. Further, in C++ I need to figure out who owns objects and who cleans them up, and also figure out how to clean up in the presence of error checking.


Without a lot of dedication, using return codes is a bug farm waiting to happen. In the C++ world, some functions return HRESULT, some return a bool, some return another set of status code, and some return a number and use an out-of-range value as an error indicator. Oh, and some are void. You not only have to write the correct code there, you have to successfully convert back and forth between the various kinds of error handling.

You also lose the opportunity to write more functional code. I end up writing something like:

CString name;

instead of writing:

string name = employee.FetchName();

And, of course, exceptions are fail-safe in that you get error reporting without doing anything, rather than having to do everything right to get error reporting.

Coherent libraries

The C++ code I'm writing uses at least 6 different libraries, all of which were written by different groups and have different philosophies in how you use them, how they're organized, how you handle errors, etc. Some are C libraries, some are C++ libraries that are pretty simple, some are C++ libraries that make heavy use of templates and/or other C++ features. They have various levels of docs, all the way from MSDN docs through "read the source" docs to "a single somewhat-outdated word doc".

I've said in the past that the biggest improvement in productivity with .NET comes from the coherent library structure. Sure, it doesn't cover everything in Win32, but for the stuff it does cover, it's often much much easier to use than the C++ alternative.

Compilation Model

C++ inherited the C compilation model, which was designed in a day when machine constraints were a whole lot tighter, and in those days, it made sense.

For today, however, separate compilation of files, separate header and source files, and linking slow things down quite a bit. The project that I'm working on now takes somewhere on the order of a minute to do a full build and link (that's to build both the output and my unit tests, which requires a redundant link). An analogous amount of C# code would take less than 5 seconds. Now, I can do an incremental make, but the dependency tracking on the build system I use isn't perfect, and this will sometimes get you into a bad state.


Reflection is a great feature, and enables doing a ton of things that are pretty hard to do in the C++ world. I've been using Source Insight recently, and while it's a pretty good IDE, it isn't able to fully parse templates, which means you don't get full autocompletion in that case.

Code == Component

In C#, you get a component automatically. In C++, you may have extra work to do - either with .IDL files or with setting up exports.

Language Complexity

C++ templates are really powerful. They can also be really, really obtuse, and I've seen a lot of those obtuse usages over the years. Additionally, things like full operator overloading are great if you want a smart pointer, but are often abused.

And don't get me started on #define.

The alternate view

So, if what I say above is true, the conclusion looks pretty clear - use C#. Not really much surprise considering who came up with the list.

But there are things that C++ has going for it, and it really depends on the kind of code you're writing which language is a better choice. In broad strokes (and in my opinion, of course), if you're doing user applications (either rich client or web), choosing C# is a no-brainer. When you start getting towards lower-level things like services or apps with lots of interop, the decision is less clear.

So, what do I think you get in C++? A few things spring to mind.

Absolute control over your memory

I think you actually need this level of control much less than you may think you need it, but there are times when you do need it.

Quick boot time

Spinning up the CLR takes extra time, and it's likely to alway take extra time  (unless it's already spun up in some other manner). You don't pay this penalty in the C++ world.

Smaller memory footprint

Since you aren't paying for the CLR infrastructure, you don't pay for memory footprint.

Fewer install dependencies

You can just install and go, and your users don't have to install the proper version of the CLR.


So, that's pretty much what I said in the class. What did I miss?

Comments (48)

  1. In the "Tools" section, I think you meant to say:

    Reflection is a great feature, and enables doing a ton of things that are pretty hard to do in the C++ world

    Note the C++, not C#.

    The outcome is not surprizing. You give some interesting points for what C++ offers, but with cost of memory, and Longhorn on the horizon, most of those points will be nullified, I’m assuming (at least on a Windows platform).

  2. . says:

    C or C++ are NOT application languages People seem to forget that.

  3. . says:

    Cross platform is a win, unless you are in the embedded market. Put aside the ego and use the right tools for the job.

  4. > What did I miss?

    Templates, template metaprogramming, STL, Boost.

  5. DrPizza says:

    "In the C++ world, some functions return HRESULT, some return a bool, some return another set of status code, and some return a number and use an out-of-range value as an error indicator. Oh, and some are void. You not only have to write the correct code there, you have to successfully convert back and forth between the various kinds of error handling. "

    Right, because these things can’t happen in C#….

    Yeah, uh huh.

  6. As an avid C++ user, I would say your points are very fair and paint an accurate picture of the problems of C++. However, I would place a caveat next to your comments on Automatic memory management. While possible in C++, resorting to the manual deletion of memory via pointers is not something that is recommended. Smart pointers, auto_ptrs, and move pointers mitigate all of the risk of manual memory management. I haven’t manually called delete in years (except when I am working with legacy C-based libraries).

    Here are a couple of advantages of C++ that I didn’t see mentioned in your article.

    1) Deterministic Destructors (DD). Having explicit knowledge of when a destructor is called leverages Resource Acquisition Is Initialization (RAII) techniques. This is just a fancy was of saying, “An object’s destructor is called when the object goes out of scope, and this destruction can be used to free resources, close handles, perform cleanup, etc.” C# has the using statement, but this is more intrusive that the syntax you get with C++.

    Also, without DD, it becomes difficult to enforce a function’s strong guarantee (an application’s state is either modified upon successful completion of the function or unchanged upon unsuccessful completion of the function or in the presence of exceptions. Think of it as a transactional function. More info: http://www.boost.org/more/generic_exception_safety.html”>http://www.boost.org/more/generic_exception_safety.html). To achieve this in any language that doesn’t have DD means wrapping each function in a try/catch block and performing undo action in the catch before rethrowing the exception. In C++, objects can be created on the stack with the undo actions in their destructors. Once the function’s processing is successful, the object’s destruction actions are dismissed. Function adapters and lambda expressions make these undo functions especially easy to create (http://www.boost.org).

    2) Policy based design. Using templates, it is possible to achieve compile time polymorphism. This design relies on a type’s capabilities rather than its abstract base class. This creates faster and, IMO, cleaner code.

    3) Template Metaprogramming. It is possible to create type containers that behave differently based on the contained type. For example, a container with an integer may provide a calculate method with the same container with a string may not provide a calculate method. In this contrived example it doesn’t sound like a good idea, but it allows remarkable syntactical consistency for container types. For an example, check out ThreadSafeObject (http://www.nwcpp.org/Meetings/2003/09.html), a type that ensures thread safety for contained objects using a clean syntax.

  7. Frisky says:

    I have been a C++ programmer for many years prior to C#. In short, C# is a refined C++.

    However, I always worry about memory management. I want deterministic destructors. (Yeah, I use IDisposable a lot, but sometimes, I know better when I want to free something.)

    I used multiple inheritence a lot. (Very similar to intefaces, but I want some default behaviour that I don’t have to code or at least requires very little code to hook up an existing implementation.)

    I really miss const functions, mutables, and volatiles. Sure, I can write stuff that does the same thing, but the compiler does not catch all the stuff I want it to catch.

    And I cannot wait for template classes, err, generics.

    I can’t wait for the refactoring tools and code snippet/template libraries I hear about in the new Visual Studio.

    I love the .Net libraries. I love the VS RAD environment. (Minus the refactoring and stuff above.)

    But most of all, I love that I can write something really cool, high tech, and blow your socks off in about 100 lines of code and 20 minutes. That is what its all about!


  8. On the C++ side:

    * Generally better exposure of CLR features, but the gap is small with C# 2.0 vs C++/CLI.

    * A better optimizing profiler.

    * And the big one – PInvoke free interop

  9. Although a .net application uses way more memory it is very smart in using it. I can allocate a 1 000 000 000 byte array without actually needing 1 Gig memory it seems as long as I don’t use all of it with C#. Also C#’s GC puts objects that are of the same generation and thus most likely to use eachother close to eachother which makes it a lot faster (CPU loads memory not directly but via the CPU cache which gets a block of a certain size, if that block contains all the objects required you are lucky). Although C++ programmers tend to say the GC is slow is very wrong. The malloc function works a bit like the GC (seeking free space), but it doesn’t clean up except when in trouble and then malloc is really slow (the GC of .net outperforms malloc by far).

    And lots of other stuff like efficient optimalization from IL to native images optimised for the cpu currently used by the ahead in time compiler. etc..

  10. Bill Clark says:

    What David Brownell said. I would also want to take issue with your statement "In C#, I usually don’t have to worry about the memory aspects." I find that in a long-running app (which is what I am working on now), memory management is much harder in C# than it is in C++. I have to worry exactly as much in both environments about who owns every new’ed object, but this is significantly more difficult in C#, where deterministic cleanup has to be the responsibility of clients and can’t be encapsulated in the resource owner. Non-deterministic cleanup is taken care of by the GC, but in a long-running app that doesn’t help me – I need to know that when I’m done with the thing, it’s gone, *now*. Yes, it’s possible to handle these problems through coding standards and thorough reviews – but this is far less effective than the guarantees you get from DD.

    Well, the GC saves me from having to worry about cyclic references. To my mind, it solves a not-very-difficult problem and replaces it with a number of very hard and insidious ones.

  11. Darren Oakey says:

    Everyone’s mentioned template metaprogramming, but I’ll throw in my agreement.

    While I’m wholeheartedly convinced that C++ is now a dead language, I really miss two things – templates and const.

    With const, you could write a very safe program, which is nearly impossible to do in C#.

    The power of templates was incredible. I’m a firm devotee of DSL’s, and templates really did allow you to basically build your own language – especially combined with typedef and (shock horror) the occasional #define.

    Generics are very good, and essential, but they just reduce the amount of code you write – they don’t take any steps towards your own domain specific language – and that’s a huge loss IMO.

  12. Alex says:

    C++ is not dead. The Windows desktop/server world is not all there is, folks.

    That said, C# is the language to program in if you’re on a Windows desktop. The only things I wish it had (and are already mentioned):

    templates — typesafe containers are very, very good things. I mean, what’s with this casting crap whenever I want to a stack in C#.

    deterministic destructors — RAII is a very good thing.

  13. SBC says:

    My preference is for C#, after having worked on C++ for numerous years ( http://weblogs.asp.net/sbchatterjee/archive/2005/01/26/361136.aspx ). Now that C# has evolved with generics – it would be nice to see comparable C# libraries that matches C++’s (incl ATL et al).

  14. Languages are all about the right tool for the right job. Now, C# has made some advancements, making it appropriate for a wider range of jobs, but when we get down to it, you’re still not going to write kernel code or device drivers or programs for extremely limited resource systems, where manual memory management is a necessity. As Alex said, the Windows desktop/server world is not all there is.

    On the flip side, there are some great uses for Perl that C# will probably never be able to compete with.

  15. Jim Lyon says:

    "What did I miss?" Two more for the C# side:

    1. C# avoids many of the dark, obtuse edge cases that follow from the not-quite-ortogonal features of C++. An example is the infamous "What happens when you call an overridden virtual method from a virtual base class’s constructor?" By not having virtual base classes and not having weird rules about when overridden methods come into play during construction, C# avoids the issue. There are many, many similar questions in C++.

    2. In modern C++, the obvious tool for the job is seldom the right tool. For example, in the modern world of STL and exceptions, you should almost never use the fundamental types of the language like pointers and arrays. Which leads one to the question "if you’re not supposed to used them, why are they there?" C# on the other hand is designed so that the obvious way to code something is usually the correct way.

  16. I second missing deterministic destructors as one of C#’s biggest annoyances. IDispose isn’t quite the same and it’s design is a bit clumsy for my taste, since you end up with repeating code including a member variable. It seems to me this would have been better implemented on object using the template method design pattern (function dispose on object that handles multiple calls and calls a protected member function onDispose() that can be overridden).

    An advantage of C# above C++ are events. Though there are libraries that bring events to C++, they all are a little bit complex and require quite an effort. It must be said, though, that C# events also are unneccesarily complex compared to the VB6 event mechanisms. To declare and trigger an event, there’s too much stupid code to be written – and suport from the IDE is missing more or less completly.

    This may be due to events relying on delgates. Delegates, however, are also a very nice feature, since they handle function pointers transparently. Typedefing a function pointer in C++ on the other hand always makes my head ache.

  17. DrPizza says:

    C++ has a set of collections classes that are worth a damn.

    C# has the .NET libraries, and they’re complete crap. Lacking in orthogonality, poorly-named, incomplete, and all-round inadequate.

  18. "C# has the .NET libraries, and they’re complete crap. Lacking in orthogonality, poorly-named, incomplete, and all-round inadequate. "

    I disagree, the naming is very consistant which is way more important than nice naming although in my opinion .net uses good naming.

    In C#2.0 there will be generics which are like templates but type safe (in c#2.0 i can do stuff like List<int> aList; etc..)

    IDisposable isn’t a replacement for the desctructor but rather a way to make sure when you call Dispose an object’s possibly native resources are disposed. You shouldnt use IDisposable if you arent dealing with native sources or other IDisposable.

    I can’t see a memory operation you can’t do with C# that you have to use in most applications. (If you want to be sure an object is finalized and deleted use GC.GarbageCollect).

    The biggest advantage is productivity. C# owns C++ in productivity. The .net class library is way easier to use (I seldomly have to look in the documentation to find out how a class works), in C++ i got to check all this stuff for the naming just sucks. C# lets you make way less bugs, using references instead of pointers really helps. Also not having to care about deleting objects is a great help. etc.. etc..

  19. <p>&lt;ul&gt;&lt;li&gt;Nehéz és hosszú szülés után… ami főleg időhiánynak köszönhető… kérjük azokat, akik szívesen olvasnak (=azt a keveset), hogyha talál vmi érdekeset, akár el is küldheti :)&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;ht

  20. DrPizza says:

    "I disagree, the naming is very consistant which is way more important than nice naming although in my opinion .net uses good naming. "

    The naming is not consistent with what the collections actually are.

    I don’t give a hoot about internal consistency; what I want is for things to be named what they ought to be named.

    Though the .NET libraries are obviously much larger than the C++ libraries, it seems to me that about as much work went into the design of the C++ libraries as went into the entire .NET class library; the result of this is that the C++ libraries are more expressive and more capable than their .NET counterparts.

  21. Erno says:

    I missed the CTS

    (How many different string types are there in C++ again? Ever tried to pass a date(time) to a database?)

  22. Denise says:

    It would be nice if you didn’t need to force someone to install the entire .net framework because you chose to write in C#.

    Since the framework is not a required download and has never been part of any major patch the majority of the Windows desktop world doesn’t have it installed.

  23. Jason Haley says:

    Interesting Finds so far this week

  24. ScanIAm says:

    A few people have mentioned a dislike for the lack of deterministic destructors in C#.

    I would like to say that it took me a while before I figured out the beauty of NOT having them. Over time, C++ caused me to blur the concept of ‘shutdown my object’ with ‘free my object memory’. These two items are distinct and different. Now, I ‘shutdown my object’ and let the OS worry about ‘freeing my object memory’. It is rare that I care about the freeing of the memory, but I DO want to know that my object has been shut down.


  25. Lington says:

    C++ is not a dead language.c# is a version of C++ and has its own loop holes as well.

    In my own opinion C++ will continue to be the best language everywhere,its library its hard-core.You can develop any applicattion you want (i.e: text base and graphical).

    It might be inflexible some somehow especially with its case sensetiveness.

    Programmer Lington(Delphi/c++/Oracle)

  26. A. Riyadi says:

    I think, both are best. It depends on what will build. Programming language is only a tools. Don’t be an extreme programming language. Some can solve many things that some could not. So, it depends on situations. As a technology preview, C# still need evolution(maybe) that makes very..very different from C family. So, what should M$ deals with ?

  27. govindarajan says:

    i have a CPP and H file and also dll created created using the same files.

    insted of this i able to refer the dll into my C# project. it is not work.

    how to convert the cPP and H file into C#

    plz send details about that to Govindarajan@teembrains.com

  28. Michael Bosley says:

    My biggest issue with C# is that it promotes "lazy" programming practices. Not that I want to sound like a drill instructor or anything, but if you can’t write good code without the helpers, then you’re going to worse code with them. (that makes me sound too much like a purist, but I can’t think of a better way to put it)

    If all objects in C# are just variants, it is going to be inherently inefficient. If I want to compare, for example, a number and a string, both would have to be converted to strings. Because I can call (x == y) with two different types in less code doesn’t make it better. It does make it easier, but see my first comment for thoughts on that.

    I don’t consider the garbage collector a significant improvement to the current method of "what you malloc you must also free." But that’s a personal opinion – some people love it. It is nice, however, that it does it during downtime so I don’t have to wait for delete/free to return… but I could do the same thing with a low priority thread.

    In C#, there isn’t a header that a developer could look at to see an object’s accessors/methods/functionality. The developer either has to read the code or get additional tools to parse the code for them. For badly formatted code (95% of us) this is tedious and error prone.

    In C#, you have to state the obvious far too often. For example, to pass something by reference, both the caller and the callee have to know it’s by reference whereas in C++ only the callee needs to know. If I want an overloaded function (or member, or accessor if you like those terms) I have to say "This can be overridden!" and then I have to say "This overrides that!".

    const. There is no guarantee that I won’t change your data.

    Maintainability. In C#, if pass by reference changes, both ends (callee and all the callers) must be changed. Alternative argument: it’s an api change.

    Efficient code is harder to write in C# than C++. (use the right tool for the job)

    Small applications have a huge startup and huge memory imprint. Large applications that need to manage memory tighter, as others in these threads have stated, shouldn’t be done in C#.

    Like Java, in order to use software developed for .Net, additional software is required to be installed. To use a coworkers phrase, it’s "coupling, gone evil-bad." 😉

  29. Eric says:


    I started to write a comment that addressed your points, but I ended up deleting it to make a general comment instead.

    While you do say some things that are true, it’s clear to me from mistakes in your comment that you haven’t really used C#.

  30. Michael Bosley says:

    Sorry, I forgot to say that I haven’t used it a lot. I’m still a newbie when it comes to C#, but I’ve been a professional programmer for the past 10 years and have developed unprofessionally before then.

    Please, feel free to comment and show me where I’m wrong… I’d like to know so I can learn and so other people don’t get the wrong ideas from what I said. 🙂

    The one comment that I know is at least "off base" is the "Small applications have a huge …" bit… I started rethinking that right after I posted, but thought I’d let others correct me.

  31. Eric says:


    I’m happy to write comments here. If you’d like to take this off-line into email, that’s okay as well.

    Here are my thoughts:

    1) Objects in C# aren’t variants. Reference types are heap-allocated the way that heap-allocated objects in C++ are (though on a managed heap), and can be converted to the type "object" merely by upcasting (since all reference types inherit from object).

    Value types are more complicated – they are stored as you would expect (ie a 4-byte integer is stored in 4 bytes) – but are convertible to object through boxing, which makes them into heap objects.

    2) In general, you can’t call == on two different types (or you can if you cast them to object, but they’ll never be equal). C# does not do the weird (IMO) thing that VB does of trying to do something in this case. You can make some comparisons between different types if the appropriate conversions exist, which is very similar to C++.

    3) Not having a header is a big advantage. Yes, you need a tool, but they’re easy to find, and having good metadata enables a ton of useful scenarios – not the least of which is much improved intellisense in IDEs. I spend much less time reading docs in C# than in C++ because of this.

    4) The decision to require ref to be placed in both places is deliberate, so the caller is clear that it’s being used. Ref is pretty uncommon in C#, since return values aren’t used for status.

    5) virtual and override are both there to make versioning better. See the reference below for more info

    6) On the subject of efficiency, it’s not clear-cut to me. I can get lower into the machine when writing in C++, which gives me an edge there, but I can write code much faster and with less effort in C#, so I have more time to spend on optimization.

    7) Small applications do take lots of memory and startup time, and that is a drawback of C#, as is the requirement to install the runtime ahead of time.

    You might also want to take a look here:


  32. Being asked this lately I thought I would post it on the blog for everyone to see and decide for themselves.

Skip to main content