Introduction structure is actually an integrated datatype, or can be considered as a derived datatype. Apart from C or C++ languages, the C# structure contains a lot of new features.
1. A structure can have Constructors Some restrictions are there when using constructors with structures. a Constructor must have minimum one argument b All the member variables must be initialized within the constructor. 2. A structure can have methods 3. Structure supports methods overloading 4. Constructors also can be overloaded 5. Structure supports Properties, Indexers and Interfaces
Example with constructors and methods
struct Point { private int x; private int y; public Point(int x) { this.x = x; this.y = x; } public Point(int x, int y) { this.x = x; this.y = y; } public void Input() { x = Int32.Parse(Console.ReadLine()); y = Int32.Parse(Console.ReadLine()); } public void Show() { Console.WriteLine("x={0}, y={1}", x, y); } }
Properties Properties are members of classes that expose member variables or objects. Properties have similarities to both fields and methods. Values are set and retrieved using the same syntax as fields Read-Only and Write-Only Properties To create read-only and write only properties, just include the relevant accessor method (get or set) and avoid the other.
Example with Properties
struct Point { private int x; public int XCoordinate { get { return x; } set { x = value; } } }
Indexers The indexer is a specialized property that allows you to expose a group of objects on the name of the object. The name used in the indexer code is always this, which indicates that the name of the object itself will be used to access the property.
Example for Indexers
struct Colors { private string[] ColorNames; public int this[int index] { get { return ColorNames [index]; } set { ColorNames [index] = value; } } }
Example for interface
interface ISample { void ShowSample(); } struct Sample : ISample { public void ShowSample() { Console.WriteLine("Sample"); } //other member definitions }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|