C# Structs

A struct is similar to a class, with the following key differences:

• A struct is a value type, whereas a class is a reference type.
• A struct does not support inheritance (other than implicitly deriving from object).


A struct can have all the members a class can, except:

• A parameterless constructor
• A finalizer
• Virtual members

A struct is used instead of a class when value type semantics are desirable. Good examples of structs are numeric types, where it is more natural for assignment to copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiation of an object on the heap. This can be important when creating many instances of a type, for example, with an array.



Struct Construction Semantics
The construction semantics of a struct are as follows:

• A parameterless constructor implicitly exists, which you can't override. This performs a bitwise-zeroing of its fields.

• When you define a struct constructor, you must explicitly assign every field.

• You can't have field initializers in a struct.


Here is an example of declaring and calling struct constructors:

public struct Point
{
int x, y;
public Point (int x, int y) {this.x = x; this.y = y;}
}

...
Point p1 = new Point (); // p1.x and p1.y will be 0
Point p2 = new Point (1, 1); // p1.x and p1.y will be 1


The next example generates three compile-time errors:

public struct Point
{
int x = 1; // Illegal, cannot initialize field
int y;
public Point() {} // Illegal, cannot have
// parameterless constructor

public Point(int x) {this.x = x;} // illegal, must
// assign field y
}

Changing struct to class makes this example legal.

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner