Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet58/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   54   55   56   57   58   59   60   61   ...   78
Bog'liq
C sharp

CHAPTER 24
Struct
The struct keyword in C# is used to create value types. A struct is similar 
to a class in that it represents a structure with mainly field and method 
members. However, a struct is a value type, whereas a class is a reference 
type. Therefore, a struct variable directly stores the data of the struct, while 
a class variable only stores a reference to an object allocated in memory.
 Struct Variable
Structs share most of the same syntax as classes. For example, the 
following struct is named Point and consists of two public fields.
struct Point
{
public int x, y;
}
Given this struct definition, a variable of the Point type can be 
initialized in the familiar way using the new operator.
Point p = new Point();


138
When creating a struct variable in this way, the default constructor 
will be called, which sets the fields to their default value. Unlike classes, 
structs can also be instantiated without using the new operator. The fields 
will then remain unassigned. However, similar to when attempting to use a 
local uninitialized variable, the compiler will not allow the fields to be read 
until they have been initialized.
Point q;
int y = q.x; // compile-time error
 Struct Constructors
Structs can contain the same members that classes can, except that 
they cannot contain destructors or parameterless constructors. The 
parameterless constructor is automatically provided and may not be 
user-defined. However, a struct may declare constructors that have 
parameters. The compiler will then enforce that all struct fields are 
assigned in the constructors, so as to avoid problems associated with 
unassigned variables.
struct Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
Chapter 24 StruCt


139
Given this definition, the following statements will both create a Point 
with the fields initialized to zero.
Point p1 = new Point();
Point p2 = new Point(0, 0);

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   54   55   56   57   58   59   60   61   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling