Thinking Parallel

A Blog on Parallel Programming and Concurrency by Michael Suess

C++ vs. C# - a Checklist from a C++ Programmers Point of View

If you're new here and like what you read, you may want to subscribe to my RSS blog feed or free email updates. Thanks for visiting!

The NetI realize for most of you this is probably old news. I have been taking a first look at C# a little while ago, because I wanted to know if it is worth looking into, and because I am thinking about polishing up my class on Parallel Programming here at the university with a little language diversification. I have taught it using POSIX Threads before, but since everyone and their grandmother seems to use Java or C# these days, throwing in a couple of examples in these languages won’t hurt. And besides, I was curious ;) . Without having written a single line of code and just by reading the various guides available, I have come up with a list of differences between C# and C++ and thought you might enjoy reading it here.

And so, without any further ado and very brief, here is my list of differences between the two, sorted into three categories: things I like better in C#, things I like better in C++ and things where I could not make up my mind. The last subheading lists the resources on the net used to compile that list:

Pro C#:

  • garbage collection
  • array bounds checking
  • huge .NET-Framework library
  • types have a defined size (e.g. a long is 64Bit)
  • strings are encoded in UTF/16
  • autoboxing - every type can be treated as if it inherits from object
  • supports constructor-chaining (one constructor can call another constructor from the same class)
  • when a virtual method is called in a constructor, the method in the most derived class is used
  • static constructors (run before the first instance of the class is created)
  • exceptions have access to a stack trace
  • advanced runtime type information and reflection
  • supports variadic functions nicely
  • built-in support for threads
  • no need for header files and #includes
  • no fall-through on switch-statements
  • arithmetic operations can be checked for overflow if required
  • objects must have a definite value before being used
  • attributes can be attached to classes and retrieved at runtime
  • no forward declarations required, classes can be arranged at will
  • access to class members / functions is done only by the dot (no more -> or ::)
  • conditional functions (e.g. for debugging)
  • structs and classes are actually different (structs are value types, have no default constructor in general cannot be derived from)
  • supports properties
  • readonly members are const, but can be changed in the constructor
  • finally block for exceptions
  • arrays are objects
  • support for anonymous functions
  • supports the base keyword for calling the overridden base class

Pro C++

  • better performance
  • portability
  • multiple inheritance
  • deterministic destruction (allows RAII)
  • any type can be thrown as exception (only classes derived from System.Exception in C#)
  • ability to enforce const-correctness
  • implicit interfaces on generics (in C#, generics must be constrained with an interface)
  • offers pointers (C# only offers pointers in unsafe mode)
  • support for macros
  • support for global variables, functions, constants
  • allows default arguments on function parameters
  • STL
  • supports bitfields

Where C# is just different from C++

  • value types and reference types exist (struct is value-type, class is reference-type)
  • value types live on the stack, reference types on the heap
  • references can point to null (must not be valid)
  • code is packaged in assemblies in C#
  • no automatic conversion from int to bool in C#
  • main-function is called Main in C#
  • no semicolon after a class declaration in C#
  • everything derives from object or can be treated as if

Resources

Disclaimer

As you can clearly see, this is not really comprehensive. The single bullet point huge .NET-Framework library would probably fill a page at least as big as this, if it was well presented. Some categorizations may also be controversial, e.g. I see portability as a huge plus for C++, while others might not care at all (or point me to Mono). Performance is also a point where I am not so sure. I expect all the nice features of C# to bring a performance-penalty into the equation, yet if you really see this in a real-world program is an entirely different matter. But since this is by no means a comprehensive treatment of the matter anyways, you are going to have to live with it - or if you can’t, you know how to use that comment button! :P

Coming to the end of this article, I have a small request: I am looking for a good book on C# development to recommend to my students (and read myself, must not forget that :P ), preferably one that is for people with a background in C/C++ and with content on threaded programming (because that’s what the class is all about). Browsing the reviews on the net, it appears that Programming C# is pretty good, judging from the table of contents it also covers threads, but of course I don’t know how well. Do you have any other recommendations? Or can you comment on whether the book would be suited for my purpose? Your comments are (as always) very appreciated!

22 Responses to C++ vs. C# - a Checklist from a C++ Programmers Point of View »»


Comments

  1. Comment by Larry O'Brien | 2007/03/06 at 21:02:36

    I wonder if you’d consider C++/CLI as something that has many of the advantages of both C# and C++.

    Anyhow, for C# tutorials with serious threading discussions, I can say with certainty that there is no book that will satisfy you. For a general tutorial, I generally recommend Liberty. For your interests and experience, I don’t hesitate to recommend Richter’s “CLR via C#” and Hejlsberg’s “C# Programming Language” (as the reference).

  2. Comment by CaffèNero | 2007/03/06 at 22:22:26

    - “abstract classes can contain code - interfaces in C# cannot”

    …err… C# has abstract classes, too. Interfaces are just…. Interfaces. And, for good OO-programming’s sake, they should NEVER contain code. So, I’d move this one to the “Pro C#” category, reformulated as:
    “C# has interfaces, C++ doesn’t”

    - “any type can be thrown as exception (only classes derived from System.Exception in C#)”

    Forgive me, but I can’t see the problem. Again, in an OO world any exception should inherit from a base class. If you need to add custom information to an exception, just make your own exception class.

    - “C++ offers pointers”

    ….Which, again, should NEVER exist in any modern language. I agree that for low-level tricks pointers may be useful, but otherwise… stick with references.

    I could go on, but I don’t want to be pedantic… (MACROS? No, seriously… :) )

    My point is that C# has its shortcomings, but you shouldn’t overlook the major semantic cleanup which it represents compared to C++. And it has Events! ;)

    Ciao,

    Alessandro

  3. Comment by Michael Suess | 2007/03/06 at 23:50:14

    Larry: I have not looked into C++/CLI more closely, but will do so shortly. Thanks for the book recommendations.

    Alessandro: thanks for the tip on abstract classes, I have taken that point out of the article. Please also note that this is a strict feature comparison, I have not said anything about how useful these features are. But of course, your input on their acutal usefulness in practice is appreciated…

  4. Comment by Kristof Gajsek | 2007/03/07 at 09:16:12

    I’d suggest “Inside C#” (Tom Archer, Andrew Whitechapel) and “Introducing Microsoft .NET” (David S. Platt). Both include chapters on multithreading.

    As far as multithreading is concerned, I think Pro C# is the ThreadPool class and lock statement, which in most cases simplify development of multithreaded code.

    Some categorizations, as you say, may be controversial. “Huge .NET library” is a big plus when you develop a server side solution, where you control the environment. When you develop a cliend side solution, this may end up as “huge additional download and install” for users, so may be placed in “Pro C++” category. :-) Also, you can not develop system stuff and device drivers in .NET.

    If I extend Alessandro: C# has its shortcomings, but if you can live with them, it sure makes your life much easier than C++. A C++/CLI may be a good merge of both worlds.

  5. SaD
    Comment by SaD | 2007/03/13 at 21:56:42

    - multiple inheritance
    You really need in multiple inheritance? I think multiple inheritance only confused when you work on big project.

    - support for global variables, functions, constants
    Global for project? Becouse C++ not clear object orieneted language. Global variables, functions, constants in C# - you can declare in main class as static.

  6. Comment by Graeme Bradbury | 2007/03/26 at 16:08:28

    The Book “Pro C# 2005 and the .NET 2.0 Platform” from Apress is a very good all round c# book.

    “CLR via C#” by Jeffery Richter is an excellent book for people who want to know how .Net under the covers works.

    There is also a free ebook on threading in C# at: http://www.albahari.com/threading/

  7. Comment by Michael Suess | 2007/04/02 at 20:46:04

    Graeme: thanks for the tip, especially the last link looks really useful. And if a Nutshell-book about .Net 3.0 is on the way (as implied by the last link), this will definitely be useful as well.

  8. Comment by Henrik Feldt | 2007/04/20 at 20:22:13

    Don’t forget the niceties that comes from being able to use the language in the common language routine! You can import visual basic assemblies, J# assemblies, PHP assemblies,
    Boo assemblies (boo.codehaus.org), Nemerle a. (http://en.wikipedia.org/wiki/Nemerle) et cetera. :)

  9. Comment by Peter Ibbotson | 2007/04/29 at 15:44:31

    Another vote for CLR via C# by Jeffery Richter possibly the most used book I have on .net.

  10. Leo
    Comment by Leo | 2007/05/05 at 16:24:10

    I learnt my .NET from Andrew Troelsen’s book on .NET 1.0 - *highly recommended*. Now there is a .NET 2.0 version available (Third Edition) and a .NET 3.0/3.5 scheduled for this year. Large books and can be intimidating at first, but easy to read once you get started. Troelsen covers most of what one needs to write code. Richter’s book is a natural follow up. More depth, less surface area.
    http://www.amazon.com/Pro-2005-NET-Platform-Third/dp/1590594193/ref=pd_bbs_sr_2/103-4941246-7143836?ie=UTF8&s=books&qid=1178374547&sr=8-2

    Regards,
    Leo

  11. foo
    Comment by foo | 2007/07/27 at 23:28:21

    Regarding C#, how is “objects must have a definite value before being used” a pro?

  12. Comment by Michael Suess | 2007/07/28 at 00:09:33

    @foo: everything that helps to prevent errors is a pro for me. And using uninitialized objects is an error I see in students code frequently - an error that would be caught by the compiler if they were using C#…

  13. Comment by Anjuna Moon | 2007/11/06 at 13:38:50

    Hm, almost half of your “positives” on the C++ list are actually the negatives that promoted the development of C#. As a veteran C++ developer I can see where you are coming from, but you shouldn’t post views on something you haven’t grasped.

    Let’s go through some of your misconceptions:

    - Better performance : What do you base this upon? C# and C++ are both just high-level programming languages. Performance is dependant on how the compilers interpret andr translate your code and nothing else.

    - Multiple inheritance && pointers: These are two of the most important differences in my opinion. MI was nothing but a root of so many problems in a multi-developer environment. The same I can say about explicit pointers. By developing the interface and delegate-features in C# these problems have decreased a lot.
    Bottom-line in the MI-issue is - if you can’t design a model using only interface-implementation and single-inheritance then you simply aren’t fit to design it.

    - Support for macros: I tend to agree a bit, but you should look into attributes of .Net to see that there is a whole lot you actually can do to interact with the compiler. Of course this applies to C++.net as well, but now I guess we are leaving the .Net part out of the discussion.

    - It is interesting to see that you give a plus to both C# garbage collection as well as the old deterministic destruction of objects. I would like to see why this ambivalence exists. If you use C++ eg. for game-programming, sure - then a lot of your points are true, especially on the det.destruction-point.
    But since you are comparing C++ to C# we are not talking about these kind of applications and therefore there is nothing that promotes your old memory-leaking problems that even the most experienced developer creates in old C++ vs. managed garbage collection.

    - Support for globals: What kind of “global” are you missing in C#? If you haven’t grasped the namespace-system then you should study some more. In a true object-oriented model there is need for only one global - the root class. If you don’t know how to develop without using “free” globals, then you should study even further ;)

    - Supports bitfields: True enough that the language itself doesn’t support this, but again we are not discussing applications where pure mapping to machine-code is essential (if we were discussing that we wouldn’t even talk about C#). However, since C# is mainly used in the .Net environment, this is not a problem since .Net offers the same bit-array-handling you have natively in C++ and a lot more manipulation-possibilities that are not there in C++. Thus, no negative.

    - STL: You have got to be kidding me or you really have no idea of the extensiveness of the .Net-library. Nuff said on that! Jeez…

    - Portability: This remains the argument in the Java-world, but the the fact is this is not (and has not been for a long time) an issue in corporate reality. The only major shift between platforms done on a global scale the last two decades have been from old Cobol-systems to either (or both) Unix/Linux and Windows.
    What an intelligent and cost-effective enterprise today does is to utilize the power of a platform and thus using the environment best suited for this purpose. Neither Java nor C++ classic can do this, just because of the platform-independentness that many of there libraries are built upon. Therefor they are actually far weaker choices as environments.

    - any type can be thrown as exception (only classes derived from System.Exception in C#): Not sure what your getting at here so please expand that. You can catch all exceptions in try-blocks, even from unmanaged components, so what is your point?

    - ability to enforce const-correctness: Dear old discussion in the C++ community but i tend to agree with Anders Hejlsberg on this subject and do not see this as a major downer.

    Well, in conclusion - C++ is naturally the given choice in real-time or close to real-time application-development, but when comparing it to C# we are mainly in the .net-world: In this environment there is in my mind no comparison and C# comes out the winner.

  14. Comment by Michael Suess | 2007/11/11 at 22:17:04

    Anjuna Moon: Thanks for sharing your thoughts here. You raise some very valid points. Unfortunately, you have chosen to spice up your points with personal attacks, which does not help your credibility at all, in my humble opinion.

    You have also misunderstood the point of the post: I have listed all the differences I could find. Yes, that means some of them are contradictory. It is not a list of things I like or don’t like about these languages. As I have posted at the very beginning of the article, I don’t even know enough about .NET to judge that.

  15. Comment by steve | 2007/12/12 at 07:26:34

    This comparison and discussion is interesting for both the content
    and the opinions of the participants. The thought that a language
    like C# can be as efficient as C++ is false. The statement C++ can
    be as efficient as C# is true. Features such as garbage collection
    are not free - I’m sorry to say. Its also interesting to see how
    some see a sortcoming (or just a decision not to support a feature)
    as a benefit. Now that’s some great spin. I’ve used multiple
    inheritence a bunch in the past and the noone ever complained.
    Sure, I can make all of my classes derive from the exception class
    so that I can throw them. No problem. But to spin this as an
    advantage is comical.

    The question I would ask is this: if MSFT hadn’t depricated all of its
    C++ libraries in favor of C#, would there be as much of it out there
    today?

    My answer would be no…

  16. Comment by programmer | 2008/01/21 at 16:40:44

    “when a virtual method is called in a constructor, the method in the most derived class is used” - *very* dangerous behaviour, c++ is better in that aspect

    “value types live on the stack, reference types on the heap” - it depends on compiler optimizations, in c++ you have the same possiblity

    “deterministic destruction (allows RAII)” - you can use that in C#

    In my opinion you should lern little more about programming.

  17. Comment by Dragontamer | 2008/03/30 at 02:50:59

    I don’t really know C# and I appreciate the list… but I do know C++ and would like to make a few comments if you don’t mind.

    * garbage collection

    C++ has 3rd party garbage collection, and in all flavors too. You can get a reference counting GC or use a Mark and Sweep one or whatever other algorithms are out there. They work pretty well and override the global operator “new” function. Check out Stroustrup’s FAQs for pointers on this part. http://www.research.att.com/~bs/bs_faq.html#garbage-collection

    * array bounds checking

    Just pointing out that you can use std::vector.at() and you’ll get bounds checking. I find it hard to think of situations when I’d use an array over a std::vector.

    * built-in support for threads

    A valid complaint, just noting that C++0x will hopefully rectify that situation :-) (Stroustrup says “C++0x will almost certainly include a threads library.” in his FAQ).

    * no fall-through on switch-statements
    * arithmetic operations can be checked for overflow if required

    These sound pretty awesome. I’ll have to look into C# just for these feature alone.

    * objects must have a definite value before being used

    I’m somewhat confused by what you mean about this. If you don’t provide a default constructor in C++, you are forced to initialize every object, or else you get a compile time error. Perhaps you mean primitives must have definite values?

  18. Comment by JAngo 6 | 2008/06/23 at 10:33:44

    This Discussion has been a GREAT help.
    I hope more teachers as well as NOOB’s would come across this site.
    Wonderful contribution.

  19. Comment by Rhonald Moses | 2008/06/23 at 12:41:51

    Hi,

    In my humble opinion, as I use both C# and C++; it’s all about what you are planning to do and how much confident are you in handling what you do.

    I don’t see much negatives in C++ as some lazy and careless coders see here. I find Multiple inheritance feature and pointers as awesome. I have hardly had the problems that are mentioned above. A half breed programmer is always half breed despite the tool he use.

    A programming language is a mere tool that helps you create what you want.

    C++ is all about endless power at developers disposal. With power comes responsibility and so, the developer is responsible to make decisions and implement.

    I personally don’t like to be limited by the inadequacy of the programming language i use. It is my job to improve as years goes by and makes caution and clean design and goals part of my programming life.

    The way I see, the only area where C++ does not fit in today’s world is where no one gives a damn about how good the developer or a particular block of code is, but all they want is some output close to what they require.

    Developers wants to feel they are good developers right out of college. C++ takes time to learn, master and it feels great when you start using it. In fact, all this years of sound existence despite the arrivals of so called safe and powerful languages speaks a lot about the language itself.

    I am excited about C++0x and the features I’ve used so far are just awesome… I am just waiting to hear C# and Java catching up with C++ on those features soon :) … Man I just love that lambda expression feature in C++0x.

    No offense to Java/C# developers (since I do C# coding too as part of my profession). It’s the same negatives you believe are +ive for C++ and I see a very bright future for C++ than any other languages.

  20. Comment by Eric | 2008/06/23 at 15:11:13

    Good information….

    But what will happen in 10 years from now…. will C# still be there?

    If I start a software project now and I know the software has a live expectancy of 10 years and more… Should I start using C# and .Net?
    I know how things went with MFC and OWL. Specially if you look at project with a poor design.

    Let me know!!!

  21. Comment by Rhonald Moses | 2008/06/23 at 15:50:43

    Hi,

    To begin with; what I am going to say is strictly my own personal opinion, based on my past experience with both the technology, what i’ve read about them and what I have observed about the future goals.

    In my humble opinion, it’s a total waste to bank on proprietary standards and proprietary programming languages. I am not against them, but the way i see it, the open technologies are leap frogging the closed technologies. I don’t see much of bright future for c# 10 years from now where the disconnected desktops does not play much significant role.

    If it still exists (c#, etc), it will be entirely incompatible with what you develop now and most importantly the windows operating systems you will be using 10 years from now will be entirely incompatible to the software you develop right now.

    For example, I had developed a small piece of utility software during my university days (8 years back) which I still use despite the evolutionary change in C++. All I had to do was to re-compile the source code with gcc4 under linux and am still using it.

    If it’s the other way around; I’ll have to either re-develop using the framework available right now (at least a major portion of the code).

    Having said that, I am not implying that there won’t be wast changes 10 years from now. 10 years is too much ahead for us to think and so I can’t be 100% certain about anything, but i have enormous faith that C++ will sustain with big backward compatibility support.

    Java might survive (I use might since i am skeptical about the growth of java base - the size of java gets complex and bigger) since it’s open sourced.

    Though mono exists, no one is certain about the future of mono and I am sure within 3 years from now, Microsoft will be at even with Linux and other *nix operating systems. So you’ll have to take your application platform independent. In those scenarios, languages such as Java, C++ (GCC, QT), Python, Perl, PHP makes much more sense than .NET.

    I leave the decision to yourself.


Trackbacks & Pingbacks »»

  1. Pingback by Jay L. T. Cornwall’s Personal Site | 2007/09/16 at 13:29:16

    […] to suppress those concerns back then but after stumbling across a post on Michael Suess’s blog comparing features of C++ with C# I’ve had second thoughts. On that impulse I’ve decided to retarget my natural rendering 3D engine […]

Leave a Reply

HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>