-2

Possible Duplicate:
When should I use a struct instead of a class?

By Venkat K in the C# .NET forum.

29-Apr-09 07:38 AM

The only difference between "class" and "struct" is that a struct defaults to having public members (both data members and function members) and a struct defaults to public inheritance, whereas a class defaults to private members and private inheritance. That is the only difference. This difference can be circumvented by explicitly specifying "public", private", or "protected" so a struct can be made to act like a class in ever way and vice versa.by convention, most programmer's use "struct" for data types that have no member functions and that do not use inheritance. They use "class" for data types with member functions and inheritance. However, this is not necessary or even universallly acepted.

*(Can this be true)

Community
  • 1
  • 1
help
  • 1
  • 4
    are you sure the author wasn't talking about C++? This is not true at all for C#, the difference between struct (value type) and class (reference type) is fundamental. – BrokenGlass Aug 14 '11 at 22:17
  • 1
    He's asking if that statement is true, I guess. This is a failure to do original research though. It's right there in the documentation. –  Aug 14 '11 at 22:17
  • http://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class – Tim Schmelter Aug 14 '11 at 22:18

3 Answers3

3

That statement is entirely false when it comes to C#. I believe it may well be true for C++, but in C# the difference is between a value type (structs) and a reference type (classes).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It's not the only difference. Structs are value types and classes are reference types. Look it up on Google to find out more about the differences, which are too many to list in the minute I have right now.

Unless, as @BrokenGlass points out it's C++.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

The statement you quote would be correct for C++, but not for C#. Here's an excerpt of what the C# Language Specification has to say about structs:

Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55