Saturday, February 17, 2007

C# from a C++ programmer

I like C#, it is overall a well thought out language, but coming from C++, there are some things you should be aware of.

Struct VS Class
C++: There isn't much difference between a struct and a class. Both can be used exactly the same way as the only difference is that a method in a struct is public by default where it is private in a class.

C#: Struct cannot be derived from unlike classes and they are always passed by value instead of by reference. What does this means? it means a lot since having a property in C# which points to a struct cannot return a reference to it but rather will return a copy of the data.

Conversion operators (casts)
C++: You can provides type conversion operators and you can make sure they point to the same memory as the original data easily.

C#: A cast operator will need to create an entire new object of the new type and thus will not reference the same memory. This is why many people advocate not using cast operators at all but instead provide conversion methods like ToMyType() as in ToString() or whatever. Casting different objects around can be very costly in C# if you don't know what you're doing. For more information read about boxing and un-boxing.

There are many other things to consider but I found those to be the 2 major points to take into consideration while switching from one language to the other.

No comments: