tags:

views:

692

answers:

10

Possible Duplicate:
Most common or vicious mistakes in C# development for experienced C++ programmers

I'm a long time C++ programmer about to start working on C# projects.

What are some conceptual changes to be aware of, and most importantly, what should I avoid doing in C# that I would normally do in C++? What bad habits do C++ programmers bring to C# that they should lose?

I have a list of C# books I intend to read. I'd like to augment that with experiences from other programmers that have made this same transition because I'll probably tend to make the same errors they did; I'd like to prevent that before it happens.

+3  A: 

Worst I have seen is

1) overly using Critical Context (locking using Monitor or lock() statement) in a web project! Result quite often is reducing IIS to a more-or-less single-threaded system.

2) Too much string processing. Used to do everything themselves so not relying on framework. Strings are immutable in C# while they are not in C++.

3) Using unsafe code because they can and not because they should.

4) Not trusting GC

Aliostad
-1 because 1, 2, 3 are true for C++ good style too. 4) is wrong. You really can't always trust it. Member system resources are an example.
ybungalobill
"4) is wrong. You really can't always trust it."Didn't I say?? :)
Aliostad
@Aliostad: *please* read my answer and give me as elegant solution as C++ gives.
ybungalobill
Yeah... you can trust the GC, until you can't of course, and then you have no clue how to fix your problem because you trusted it implicitly for so long.
Ed Swangren
@Ed come on Ed,you cannot be serious GC works. It works for Java, works for C#, and all those dynamic languages out there. I actually have done fair bit of C++ doing heavy image processing and I managed my memory alright, never had leaks but coding in C# is less coding thanks to .NET Fx.
Aliostad
how are 1 and 2 specific to C++ programmers?
jalf
Jalf Didn't you see what I wrote: "I have seen"... but generally C++ coders will use locking more since they are already aware of multi-threading while average C# coder is not.
Aliostad
+8  A: 

Just one example:

In C++ there is no difference between a struct and a class. Over the years this has led groups and individuals to define their own rules for using one over the other.

In C# there is a concrete difference. A struct is a value type and a class is a reference type.

When C++ programmers bring thier old, arbitrary class/struct definitions to C#, unexpected things tend to happen.

Here is a fairly good read for C++ programmers moving to C#: http://msdn.microsoft.com/en-us/magazine/cc301520.aspx

Tergiver
They do behave differently, but the compiler usually yells at you when you've used them incorrectly, no? It's usually not a run-time error? At least in my experience...
Mark
Just the fact that a class is reference type and a struct is a value type will cause unintended issues, such as when you pass it into a method and are expecting the original object to be modified. It also can easily bloat the memory usage due to all the unintended copying. These issues won't be caught at compile or run-time, and have to be manually debugged.
KallDrexx
+3  A: 

The big ones:

  • C# doesn't have multiple inheritance, it uses interfaces instead.
  • You can't control the lifetime of an object or use that to your advantage.
  • The C# equality operator doesn't always do what you think it should. Sometimes it compares the content of a variable and sometimes the address of the variable.
Jay
You can, and absolutely must control the lifetime of objects in a GC environment. Mind your references!
Tergiver
Removing all references doesn't mean the end of an objects life, unless you force GC. This is why you also have IDisposable and using to clean up other resources faster. The control of the lifetime is alot looser.
Greg Domjan
@Greg: There's nothing wrong with your logic. What I object to is the attitude of complacency. From your application's point of view, an object is dead and gone when it no longer holds a reference. A garbage collector is a simulation of a system with infinite memory. The problem is that it is only a simulation and we know that there isn't infinite memory. That means that we are still responsible for object lifetime.
Tergiver
@Greg part 2: IDisposable and the lifetime control of external resources are a different subject altogether.
Tergiver
@Tergiver: I agree but I was trying to make a different point. In C++ I can use scope to cause object destruction. I can use that to my advantage. One example is a class that changes the cursor to an hourglass and restores it in the destructor. Or the example here http://jaysprenkle.wordpress.com/2010/09/04/managing-critical-sections-using-scope-in-c/
Jay
+1  A: 

Not much, moving from C++ to C# is a sort of degradation, so you can't do "Bad things". The only thing I can think of is relying on automatic memory management:

class A {
    ofstream file;
public:
    // bla bla
};

In C# you need to implement all the IDisposable garbage to not leak the file... You can easily forget it.

Bad C# programmer behaviors in C++ would be a more interesting topic.

ybungalobill
If you correctly implement it (IDisposable+Finalizer) then even if you forget, GC will kick in - although it will not be immediate. If you are supposed to forget, in C++ there are so many things you will forget! All those memories you have to release manually...
Aliostad
@Aliostad: implementing IDisposable won't much. If you loose A GC will close file anyway, even without IDisposable. But it may never happen. Unlike C# I don't release memory (or other resources) manually in C++. Heard about RAII? It solves almost all the problems, at least much more than GC does.
ybungalobill
RAII to the rescue :)
Matteo Italia
Yeah really, I don't get it. All the pro-GC people, you really think that most of my resources are memory? Most of them are external resources or memory objects representing external resources. Those resources must be freed in deterministic fashion.
ybungalobill
@Aliostad: there's no guarantee that the finalizer will ever run.
jalf
@jalf If you need guarantee, then you use CriticalFinalizerObject.
Aliostad
moving the goalposts. :) My point was simply that if you implement IDisposable+ finalizer, the GC is *not* guaranteed to kick in. Sure, you can work around that if you're willing to plow through those 2 pages of additional requirements and constraints in order to make your code a CER so you can use a CriticalFinalizerObject so you can be sure the finalizer will run.......... but really... That's hardly the same as "correctly implemneting IDisposable+Finalizer" which was the starting point.
jalf
+1  A: 

Things to change when moving from C++ to C#:

  • Use properties when possible to represent class member data
  • Use interfaces in situations that might call for multiple inheritance in C++
  • Use events for notification instead of handing callback functions (delegates) to classes
  • Remember to use the using() {} construct to ensure that resources like files and DB connections are disposed when they go out of scope.

That's just off the top of my head

RyanHennig
+1  A: 

The biggest shift for me was to stop worrying about freeing memory, thread safety (I mean you still have to lock things, but C# is designed for threading from day 1 so there are no nasty gotchas) and header files.

If you feel tempted to use /unsafe you are almost certainly wrong.

Learn the class library.

pm100
+8  A: 

One thing to be aware of is that C# doesn't have destructors in the same sense as C++ does. A method with the signature of a C++ destructor is called a finalizer in C# and it's not necessary (and in some cases not recommended) to implement those.

Check out the IDisposable interfaceand these articles on garbage collection: Everybody thinks about garbage collection the wrong way and Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework.

Anna Lear
I wonder how hard it would have been for Microsoft to have added something analogous to a "Using" tag to the declaration of an iDisposable field, to indicate that the field should be ".disposed" when the object itself is. Otherwise it is difficult to ensure the disposal of iDisposable objects that are created via initializations (rather than in the constructor).
supercat
Actually it is called a **destructor** in the C# world. For worse.
Maciej Hehl
+1 for a very interesting read!
TokenMacGuy
+2  A: 

There's stuff you can do in C++ that you can't do in C#, and vice versa. They aren't likely to cause you problems.

Biggest change - getting rid of the "instantiation is initialization" mindset. Garbage collection means you don't need to worry about allocating or freeing memory (except when you do), but it also means you can't rely on something falling out of scope triggering the destructor to clean up after you.

Learn the "using" construct, in C#, and make sure you use it.

Second change - in C++ "class" and "struct" are effectively synonyms. In C#, they are very different things.

Jeff Dege
A "using" block provides something analogous to C++ behavior of disposing resources when the block exits. Unfortunately, there's no way to tag fields for automatic disposal when an object itself is disposed, nor is there any pleasant way of cleaning up an object whose initialization fails.
supercat
+1  A: 

It's not a "bad" habit, but something you definitely need to keep in mind when switching from C++ to C#: relying on destructors to do your cleanup. Instead, you need to remember to implement IDisposable and control your object's lifetime by a using statement.

Alex Emelianov
+5  A: 
  • there is no implicit RAII, you have to explicitly code it
  • there is no const protection
  • properties are pairs of methods, not a value
  • when iterating you start before collection and end at the end of it (in terms of C++)
  • foreach is like using const_iterator
  • List as the name says, is not a list, is a an array
  • generics are resolved at their compile time, not at time of using them
macias