Thursday, 21 July 2011

Difference between struct and class in c#


Feature
Struct
Class
Notes
Is a reference type?
No
Yes

Is a value type?
Yes
No

Can have nested Types (enum, class, struct)?
Yes
Yes

Can have constants?
Yes
Yes

Can have fields?
Yes
Yes
Struct instance fields cannot be initialized, will automatically initialize to default value.
Can have properties?
Yes
Yes

Can have indexers
Yes
Yes

Can have methods?
Yes
Yes

Can have events?
Yes
Yes
Structs, like classes, can have events, but care must be taken that you don’t subscribe to a copy of a struct instead of the struct you intended.
Can have static members (constructors, fields, methods, properties, etc.)?
Yes
Yes

Can inherit?
No
Yes
Classes can inherit from other classes (or object by default). Structs always inherit from System.ValueType and are sealed implicitly
Can implement interfaces?
Yes
Yes

Can overload constructor?
Yes
Yes
Struct overload of constructor does not hide default constructor.
Can define default constructor?
No
Yes
The struct default constructor initializes all instance fields to default values and cannot be changed.
Can overload operators?
Yes
Yes

Can be generic?
Yes
Yes

Can be partial?
Yes
Yes

Can be sealed?
Always
Yes
Structs are always sealed and can never be inherited from.
Can be referenced in instance members using this keyword?
Yes
Yes
In structs, this is a value variable, in classes, it is a readonly reference.
Needs new operator to create instance?
No
Yes
C# classes must be instantiated using new. However, structs do not require this. While new can be used on a struct to call a constructor, you can elect not to use new and init the fields yourself, but you must init all fields and the fields must be public!

No comments:

Post a Comment