Section94.1:Declaringa struct
publicstructVector
{
publicintX;
publicintY;
publicintZ;
}
publicstructPoint
{
publicdecimalx,y;
publicPoint(decimalpointX,decimalpointY)
{
x=pointX;
y=pointY;
}
}
- structinstancefieldscanbesetviaaparametrizedconstructororindividuallyafterstructconstruction.
- Privatememberscanonlybeinitializedbytheconstructor.
- structdefines a sealed type that implicitly inherits from System.ValueType.
- Structs cannot inherit from any other type, but they can implement interfaces.
- Structsarecopiedonassignment,meaningalldataiscopiedtothenewinstanceandchangestooneofthem are not reflected by the other.
- Astructcannotbenull,althoughitcanusedasanullabletype:
Vectorv1=null;//illegal
Vector?v2=null;//OK
Nullable<Vector>v3=null//OK
- Structscanbeinstantiatedwithorwithoutusingthenewoperator.
//Bothoftheseareacceptable
Vectorv1=newVector();v1.X=1;
v1.Y=2;
v1.Z=3;
Vectorv2;
v2.X=1;
v2.Y=2;
v2.Z=3;
However,thenewoperatormust be usedin orderto usean initializer:
Vectorv1=newMyStruct{X=1,Y=2,Z=3};//OK
Vectorv2{X=1,Y=2,Z=3};//illegal
Astructcandeclareeverythingaclasscandeclare,withafewexceptions:
- Astructcannotdeclareaparameterlessconstructor.structinstancefieldscanbesetviaaparameterized constructororindividuallyafterstructconstruction.Privatememberscanonlybeinitializedbythe constructor.
- Astructcannotdeclaremembersasprotected,sinceitisimplicitlysealed.
- . Struct fields can only be initialized if they are const or static.
Withconstructor:
Vectorv1=newVector();
v1.X=1;
v1.Y=2;
v1.Z=3;
Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z);
//OutputX=1,Y=2,Z=3
Vectorv1=newVector();
//v1.Xisnotassigned
v1.Y=2;
v1.Z=3;
Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z);
//OutputX=0,Y=2,Z=3
Pointpoint1=newPoint();
point1.x=0.5;
point1.y=0.6;
Pointpoint2=newPoint(0.5,0.6);
Withoutconstructor:
Vectorv1;
v1.Y=2;
v1.Z=3;
Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z);
//OutputERROR“Useofpossiblyunassignedfield’X’
Vectorv1;
v1.X=1;
v1.Y=2;
v1.Z=3;
Console.WriteLine(“X={0},Y={1},Z={2}”,v1.X,v1.Y,v1.Z);
//OutputX=1,Y=2,Z=3
Pointpoint3;
point3.x=0.5;
point3.y=0.6;
If we use a struct with its constructor, we aren’t going to have problems with unassigned field (each unassigned field has null value).
Unlike classes, a struct doesn’t have to be constructed, i.e. there is no need to use the new keyword, unless you need to call one of the constructors. A struct does not require the new keyword because is a value-type and thus cannot be null.
Section94.3:Structsarecopiedonassignment
Sinse structs are value types all the data is copiedon assignment, and any modification to the new copy does not changethedatafortheoriginalcopy.Thecodesnippetbelowshowsthatp1iscopiedtop2andchangesmadeon p1does not affect p2instance.
varp1=newPoint{ x=1,
y=2
};
Console.WriteLine($”{p1.x}{p1.y}”);//12
varp2=p1;
Console.WriteLine($”{p2.x}{p2.y}”);//Sameoutput:12
p1.x=3;
Console.WriteLine($”{p1.x}{p1.y}”);//32
Console.WriteLine($”{p2.x}{p2.y}”);//p2remainthesame:12
Section94.4:Structimplementinginterface
publicinterfaceIShape
{
decimalArea();
}
publicstructRectangle:IShape
{
publicdecimalLength{get;set;}
publicdecimalWidth{get;set;}
publicdecimalArea()
{
returnLength*Width;
}
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter110:Timers 10/05/2024
- Chapter109:Stream 09/05/2024
- Chapter108:CheckedandUnchecked 08/05/2024