Reputation: 9870
Is it true to say that a struct is just a class which inherits from System.ValueType?
Is the keyword "struct" just syntactic sugar for writing a class with : System.ValueType after the name?
If it is just a class, then is it true to say that not all classes are reference types since structs are technically classes?
Upvotes: 3
Views: 1037
Reputation: 38397
Not quite "just syntactical sugar". From the MSDN:
Although ValueType is the implicit base class for value types, you cannot create a class that inherits from ValueType directly. Instead, individual compilers provide a language keyword or construct (such as struct in C# and Structure…End Structure in Visual Basic) to support the creation of value types.
So could you say that a struct
is just a class
that inherits from System.ValueType
semantically? That'd debatable. All struct
are derived from System.ValueType
, but you can't explicitly create a class
that derives from System.ValueType
.
In addition, of course, just being derived from System.ValueType
, struct
has a lot of differences from class
as you probably know. But if not, I have a blog post on some of the key differences here, including but not limited to:
struct
cannot accept initialization values for their fields in the definition (they always given values for their declared field types).struct
can have events, but since they are value types must take care that you aren't subscribing to a copy!struct
.struct
parameterless constructor, struct
provides one which cannot be overridden.struct
constructor does not hide the parameterless constructor.this
keyword, used in a struct
is a value variable, not a reference.new
to create an instance of a struct
(but if you do this you must provide a value for all fields before it is used.MSDN also has some good advice on when to use struct
vs class
. Because they are value types, you should think of them as such and limit them to smaller things (16 bytes or less) and preferably as immutable representations of a single value (like DateTime
, TimeStamp
etc.).
Upvotes: 11
Reputation: 65534
Structs differ from classes in several important ways:
See also: Choosing Between Classes and Structures
Upvotes: 5