struct C# with Example



struct C# with Example

A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the 
coordinates of a rectangle or the characteristics of an item in an inventory. 
Classes are reference types, structs are value types. 
using static System.Console; 
namespace ConsoleApplication1 
{ 
struct Point 
{ 
public int X; 
public int Y; 
public override string ToString() 
{ 
return $"X = {X}, Y = {Y}"; 
 

} 
public void Display(string name) 
{ 
WriteLine(name + ": " + ToString()); 
} 
} 
class Program 
{ 
static void Main() 
{ 
var point1 = new Point {X = 10, Y = 20}; 
// it's not a reference but value type 
var point2 = point1; 
point2.X = 777; 
point2.Y = 888; 
point1.Display(nameof(point1)); // point1: X = 10, Y = 20 
point2.Display(nameof(point2)); // point2: X = 777, Y = 888 
ReadKey(); 
} 
} 
} 
Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and 
nested types, although if several such members are required, you should consider making your type a class instead. 
Some suggestions from MS on when to use struct and when to use class: 
CONSIDER 
defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly 
embedded in other objects. 
AVOID 
defining a struct unless the type has all of the following characteristics: 
It logically represents a single value, similar to primitive types (int, double, etc.) 
It has an instance size under 16 bytes. 
It is immutable. 
It will not have to be boxed frequently. 

0 Comment's

Comment Form

Submit Comment