Reputation: 3325
is there a difference between a struct in c++ and a struct in c#?
Upvotes: 26
Views: 8997
Reputation: 51711
Structs in C# very different from classes, see Structs vs Classes for more
Structs in C++ are identical to classes, EXCEPT that members are public by default. Other than that, a C++ struct can do everything a C++ class can do.
Upvotes: 14
Reputation: 29174
In C# you use structs to define value types (as opposed to reference types declared by class
es).
In C++, a struct is the same thing as a class with a default accessibility level of public
.
So the question should be: are structs in C# different from classes in C++ and, yes, they are: You cannot derive from C# structs, you cannot have virtual functions, you cannot define default constructors, you don't have destructors etc.
Upvotes: 29
Reputation: 238116
A C# struct is managed code, which will be freed by the C# garbage when nobody refers to it anymore. Its destructor is called whenever the garbage collector decides to clean it up.
A C++ struct is an unmanaged object, which you have to clean up yourself. It's destructor is predictably called when you delete it, or it goes out of scope.
Upvotes: 0
Reputation: 89671
Are you trying to interoperate between managed C++ and C#? If so, there are extensions to C++ to allow this: see link
Upvotes: 0
Reputation: 78595
Yes.
structs in c# are plain old, by value, data types (as opposed to classes that are by reference and have ll the OO stuff)
structs in c++ are just class that are public by default.
Upvotes: 0