A structure is a value type, which is usually used to encapsulate a group of related variables. The structure can contain constructors, constants, fields, methods, attributes, operators, events, and nested types, however, if the preceding types are included, you should consider using classes.
Structure Features:
· Structured value type
· When passing a structure to a method, the structure is passed by passing the value instead of being passed as a reference.
· The new operator is not applicable to structure instantiation.
· The structure can declare constructors, but they must contain parameters
· One structure cannot inherit from another structure or Class
· The structure can implement interfaces
· It is incorrect to initialize the instance field in the structure.
The following is an example of some features:
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace _
{
Class Program
{
Public struct Rect // define a rectangular structure
{
Public double width; // The width of the rectangle.
Public double height; // The height of the rectangle
/// <Summary>
/// Constructor to initialize the width and height of the rectangle
/// </Summary>
/// <Param name = "x"> width of the rectangle </param>
/// <Param name = "y"> height of the rectangle </param>
Public Rect (double x, double y)
{
Width = x;
Height = y;
}
/// <Summary>
/// Calculate the rectangular area
/// </Summary>
/// <Returns> rectangular area </returns>
Public double Area ()
{
Return width * height;
}
Public double CArea (double r)
{
Return 3.14 * r;
}
}
Static void Main (string [] args)
{
Rect rect1; // instantiate the rectangular structure
Rect1.width = 5; // returns the width of a rectangle.
Rect1.height = 3; // assign a value to the height of the rectangle
Console. WriteLine ("rectangular area:" + rect1.Area ());
Rect rect2 = new Rect (6, 4); // use the constructor to instantiate the rectangular structure.
Console. WriteLine ("rectangular area:" + rect2.Area ());
Console. WriteLine ("the area of the circle is:" + rect2.CArea (10 ));
Console. ReadLine ();
}
}
}