C# Structure with programming Examples


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:

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.

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):

The methods of the structure can also be called using the point operator.

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.

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.

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.

  • 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:

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:

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:

or (ToString is then automatically applied to p because the first member of the expression is already a string):

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):

One structure can incorporate another structure. In the following example, StructInt (for structure interior) can be defined before or after StructExt (for exterior structure):

StructInt could have been defined in StructExt:

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:

We create two variables of type S and C in the same way:

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:

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:


C# Structure

How to use nested Structure in C# Programming:


C# Structure

How to use methods in C# Structure:


C# Structure

How to use the concept of overloaded methods in c# Structure:


C# Structure

How to use the concept of operator overloading in c# structure:


C# Structure

Related Article:

Enumeration in c#

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: