Saturday, July 16, 2011

Structs vs Classes C# and C++

Someone may argue:
in C++ Structs are largely redundant Why C# still have them & not discarded it like multiple inheritance ?

Here is the answer :

In C++, a struct and a class are pretty much the same thing.
The only difference is the default visibility level (public for structs, private for classes).

However, in C# structs and classes are different.
1) In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap).Classes are accessed indirectly using reference.
2) Structs can implement interfaces but cannot inherit from structs or classes, .
3) Structs cannot have destructors.

we can say ......
A C# struct is much more like a C struct than a C++ struct.

Hope it make this concept pretty clear!

No comments:

Post a Comment