tags:

views:

309

answers:

5

is there a difference between a struct in c++ and a struct in c#?

+9  A: 

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.

Binary Worrier
C# structs can have constructors - they just can't have a *default* constructor.
Marc Gravell
Marc: You spotted my intentional mistake there, well done . . . p.s. I fixed it :)
Binary Worrier
@Marc: They always have a default constructor, you just can't define your own one :-)
MartinStettner
Guys, you'se would all be awful disapointed if I didn't give ye things to be pointing out to me, be honest now . . .
Binary Worrier
@MartinStettner - actually, according to the CLI spec they **never** have a default constructor. The C# compiler just lies ;-p
Marc Gravell
A: 

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.

BCS
A: 

Are you trying to interoperate between managed C++ and C#? If so, there are extensions to C++ to allow this: see link

Cade Roux
A: 

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.

Andomar
C# structs are not objects; they are not *themselves* subject to garbage collection (unless they are fields on a type that *is* garbage collected, i.e. a class). C# structs cannot define a finalizer: "Error 1 Only class types can contain destructors"
Marc Gravell
Good point about the finalizer. But structs are objects I think: "MyStruct is object" returns true. And somebody has to free the memory the struct uses; the garbage collector will do that, if the struct is on the heap.
Andomar
+11  A: 

In C# you use structs to define value types (as opposed to reference types declared by classes).

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.

MartinStettner
Martin's point about C# structs being value types is quite important for performance because they have to be boxed and unboxed for some operations. Please read up on "boxing" if you must worry about performance.
dss539