C# Structure with programming Examples
Structures
C# Structure:- In the C language, structures were an important cornerstone of the underlying data model because only they allowed the programmer to define his own compound types. In C++, the Structure their prominent position. The newly introduced concept of the class was not only more powerful, but also formed the basis for object-oriented programming in C++. In C#, the Structure through consistent specialization and delimitation from the class (structures are in C# value types, while classes are reference types) again gained in importance, but overall remains she is also the little brother of the overwhelming class in C#. In this sense, structures are presented here primarily in comparison to the class concept. Important Features and syntax forms such as the definition of fields and methods, the assignment of access modifiers.
C# Structure Definition:
While arrays are used to combine several variables of the same type, you can use c# structure combine several variables of different types. Of course, this only makes sense if the variables logically belong together e.g. the two coordinates of a point in Cartesian Coordinate system:
1 2 3 4 5 6 7 8 9 |
struct point { public int X; public int Y; } |
The definition is introduced with the keyword struct, followed by the name of the structure. After that follow the members of the structure in curly brackets.
C# Structure with fields and a method:
Structures can be essentially the same Like classes, members contain fields, constants, methods, Property or type declarations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
struct point { public int X; public int Y; public void Move (int dx, int dy) { X + = dx; Y + = dy; } } |
Uses of C# Structure:
C# structures are types of values. If you define a variable of a structure type, a c# structure Creates an object that contains its own copy of each field in the structure. This c# structure object becomes (unlike objects of classes) stored directly in the memory of the variables. You can access the fields of the c# structure object using the variable name and the dot operator (if the fields in the structure are declared as public):
1 2 3 4 5 |
Point p; p.X = 100; p.Y = 5; |
The methods of the structure can also be called using the point operator.
1 2 3 |
p.Move (-50, 7); Console.WriteLine (p.X + "," + p.Y); // output 50.12 |
C# Structure members are private by default; . they can only be used within the structure definition become. Members that should also be accessible via structure variables must be declared as public become. Â C# Structure objects can also be created explicitly with the new operator.
1 |
Point p = new point(); |
However, the new operator does not, as one might assume, that the structure object now like a class object stored on the heap instead of on the stack (i.e. in the structure variable) becomes. The new syntax here only means that the structure object with the standard constructor of the Structure is generated. Every C# structure has such a standard constructor (constructor without Parameter), which initializes the fields of the structure with the standard values ​​of their types.
Note:The values ​​of structure fields can only be queried and used after they have been assigned.
1 2 3 |
Point p; Console.WriteLine(p.X + "," + p.Y); // generates an error message from the compiler |
Using the new syntax saves unnecessary error messages because the constructor initializes the fields of the structure.
Differences between c# structure and classes:
Despite their close relationship and the many similarities in syntax and usage, there are at least just as many differences between structures and classes. In particular, there are two of these differences semantically significant:
- Structured variables are of type “value” (like int, float, etc., but not strings) while the real objects (variables of a class) are of type “reference”. The variables structures are therefore directly coded in a memory area allocated on the stack while that the objects are allocated in another memory area (the heap) and are only accessible via a “reference” (actually a kind of pointer that doesn’t dare say its name). Access to structured variables are therefore faster than object accesses (although the difference is measured in tens of nanoseconds).
- Not all object-oriented concepts are supported for structures. The most important point here is certainly that structures cannot be inherited. So that is missing Structures are not only an important means of code recycling, but also the basis for that Polymorphism and the implementation of generic solutions.
- Structures cannot inherit any class or structure and cannot be used as a basis for no derived classes or structures. The Object class (more precisely, the ValueType class directly derived from the Object class, but this ValueType class does not provide any property or complementary method) can however be considered as the base class of any structure but this is also the case for primitive types (int, double, string, etc.) which, too, can be considered as objects of the classes derived from Object that are the Intxy classes (xy being at replace by 8, 16, 32 or 64 depending on the type), Single, Double, String, etc.
- The fields of a structure cannot be explicitly initialized in the definition even of the field (unlike the fields of a class).
- A structure can contain zero, one or more constructors but no constructor by default (in other words, no constructor without arguments).
Structures are therefore mainly used in C# for types that have only a few fields with little Memory requirements (otherwise the typical copying of the structures for value types would be required for Assignments and parameter transfers to an unreasonably large load on memory and processor) and which can neither be derived from other types nor as a starting point for type Hierarchies seem suitable (not possible due to a lack of inheritance).
There are also a number of other differences that are semantically less important, theirs The programmer should be aware, however, that he does not want to constantly receive complacent error messages from the Compilers will face:
- All structure members are implicitly private.
- Structure members can only be declared as private or public.
- Fields of structures cannot be initialized in the structure definition.
1 |
public int Field = 1;Â // Error |
- the default constructor of structures can be overloaded with other constructors, but not through your own implementation can be replaced.
- Structures cannot define a destructor.
- All structures are based on the base class System.ValueType, which in turn is derived from Object. Methods inherited from ValueType can be overwritten in structures with override.
- Structures cannot be derived explicitly from classes.
Since there are many similarities between structure and class, in which case would you prefer to use a structure? In the case where the structure is limited to a few bytes (certainly not more than eight) because we avoids the allocation of a reference (on the stack) and a pointed area (on the heap). With the C# structure, we have only the allocation of the structure (and nothing else) on the stack. As soon as the definition includes more than fields, the gain through structures becomes less obvious. This gain even turns into a loss during the passing arguments (because you have to copy more bytes onto the stack). The use of classes is essential whenever it comes to enjoying the benefits of inheritance, not possible with structures. Our structured variable p could have been declared by new but in a completely equivalent way (by compared to the simple data d) regarding the memory allocation and the final result:
1 |
data d = new data(); |
d (in other words, its two fields Name and Age) would also have been allocated on the stack, like any variable of type value (int, double, etc.) but its fields are initialized to zero (to an empty string for Name). For to illustrate this remark, consider the two ways of declaring a c# structured variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
struct data { public int Age; } ..... data d1; data d2 = new data(); Console.WriteLine(d1.Age);Â // syntax error: d1.Age not initialized Console.WriteLine(d2.Age); // no problem |
With this difference (initialization of fields), declare a C# structure variable (without constructor, remember) as we did for d1 or as we did for d2 is equivalent. In either case, memory allocation is done on the stack. A structure can implement one or more constructors (but not a constructor without arguments) as well as methods, which allows, in particular, to render fields of the structure private. To create a structured variable using one of its constructors, it is imperative to create with new (but the compiler realizes that this is a structured variable and allocates it then on the stack, without the slightest notion of reference). In the following fragment, we implement a constructor and redefine the ToString method which converts a c# structure variable to a string of characters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
struct data { string Name; int Age; public data (string N, int A) {Name = N; Age = A;} public override string ToString() {return Name + "(" + Age + ")";} } ..... data d = new data("Fawad khan", 27); To display d, we then write: Console.WriteLine(d.ToString()); |
or (ToString is then automatically applied to p because the first member of the expression is already a string):
1 |
Console.WriteLine("Data:" + d); |
This display gives:
Data: Fawad khan(27)
The Name and Age fields of d, which are now private, are no longer accessible outside the functions of the structure (in other words, in the previous case, outside the constructor and the function ToString). This is a good programming method since it hides the operation internal structure.
If the c# structure includes a constructor and you declare an array of structures, you must explicitly call the constructor for each cell in the table (because no constructor is automatically called for a table cell). For example (creation of a table of ten people):
1 2 3 |
data[] td = new data[10]; for(int i = 0; i <td.Length; i ++) td[i] = new data ("?", -1); |
One structure can incorporate another structure. In the following example, StructInt (for structure interior) can be defined before or after StructExt (for exterior structure):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
struct StructInt { public int si1; public int si2; } struct StructExt { public StructInt sesi; public int se1; } ..... StructExt s; s.sesi.si1 = 10; |
StructInt could have been defined in StructExt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
struct StructExt { struct StructInt { ..... } public StructInt si; } |
With StructInt defined inside StructExt, you can no longer create a variable of type StructInt outside of StructExt, but we can nevertheless declare (anywhere but the definitions must be of structures are known):
StructExt.StructInt sesi;
There are certainly similarities between the struct and class types, but the fundamental difference is this one: struct is a value type while class is a reference type. To illustrate this difference, let’s create a c# structure and a class covering the same fields:
1 2 3 |
struct S {public int x, y;} class C {public int x, y;} |
We create two variables of type S and C in the same way:
1 2 3 |
S p1 = new S (); p1.x = 10; p1.y = 20; C p2 = new C (); p2.x = 10; p2.y = 20; |
p1 occupies a single memory area which accommodates two integers. p2 occupies two memory areas: one for the reference (which indicates where the data area is located) and an area containing the data itself (the x and y fields). Now let’s declare and initialize the two variables p3 and p4:
1 2 3 |
S p3 = p1; p3.x = 100; C p4 = p2; p4.x = 100; |
The effect is not at all the same!
All the contents of p1 are copied to p3. p1 and p3 are quite distinct variables and modify p3.x has no effect on p1.x.
On the other hand, p4 designates a reference, initialized to p2. p2 and p4 certainly constitute two distinct zones (like p1 and p3) regarding the “reference” part but point to the same and unique data area. Modifying p4.x therefore modifies p2.x. We would have created two very distinct variables (both for the reference part than for the given part) with an instantiation by new.
Programming Examples of C# Structure:
How to use simple C# Structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace demo { class Program { public struct info { public string Name; public int Age; } static void Main(string[] args) { info data1; data1.Name = "Fawad khan"; data1.Age = 26; Console.WriteLine("Name is " + data1.Name + ", age is " + data1.Age); Console.ReadLine(); } } } |
output:
How to use nested Structure in C# Programming:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace demo { class Program { public struct Contact { public string address; public int no; } struct info { public string Name; public int Age; public Contact c; } static void Main(string[] args) { info data; data.Name = "Fawad khan"; data.Age = 26; data.c.address = "Pakistan"; data.c.no = 123456789; Console.WriteLine("Information:"); Console.WriteLine("Name: " + data.Name); Console.WriteLine("Age: " + data.Age); Console.WriteLine("Country: " + data.c.address); Console.WriteLine("phone No: " + data.c.no); Console.ReadLine(); } } } |
output:
How to use methods in C# Structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace demo { struct data { static int x = 200; static int y = 299; public void values(int i, int j) { x = i; y = j; } public static void Sum() { int sum = x + y; Console.WriteLine("The sum is {0}", sum); } } class Program { static void Main(string[] args) { data d = new data(); d.values(40, 10); data.Sum(); Console.ReadLine(); } } } |
output:
How to use the concept of overloaded methods in c# Structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace demo { struct data { static int x = 10; static int y = 20; public void Value_XY(int i, int j) { x = i; y = j; } public void Value_XY(int i) { x = i; y = i; } public static void Sum() { int sum = x + y; Console.WriteLine("The sum is {0}", sum); } } class Program { static void Main(string[] args) { data d1 = new data(); data d2 = new data(); d1.Value_XY(100, 200); d2.Value_XY(50); data.Sum(); Console.ReadLine(); } } } |
output:
How to use the concept of operator overloading in c# structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace demo { struct data { private int x; private int y; public data(int i, int j) { x = i; y = j; } public void value() { Console.WriteLine("{0} {1}", x, y); } public static data operator -(data d1) { data d = new data(); d.x = -d1.x; d.y = -d1.y; return d; } } class Program { static void Main(string[] args) { data data1 = new data(30, 10); data1.value(); data data2 = new data(); data2.value(); data2 = -data1; data2.value(); Console.ReadLine(); } } } |
output: