TechCognition

Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

Understanding Structures

Structures are value types which are stored on stack. Structure is “lightweight class type” which is well suited for mathematical operations.

Structures are user-defined type and structures are types that can contain any number of data fields and members that operate on these fields.

Structures can define constructors, can implement interfaces, and can contain any number of properties, methods, events, and overloaded operators.

Structures are created using the struct keyword. Here we define new structure Sum which will give the addition of two numbers by using Add() method.

struct Sum
{
        public int x;
        public int y;

        public void Add()
        {
          Console.WriteLine("Addition of {0} and {1} : {2} ", x, y, (x + y));
        }
 }

Now create variable for structure Sum and pass values for x and y. If you are not passing x and y values it will produce the compile time errors.

This will produce the compile time errors


               Sum obj;
          //  obj.x = 10;
           // obj.y = 20;
            obj.Add();

 

This will display addition of two numbers


            Sum obj;
            obj.x = 10;
            obj.y = 20;
            obj.Add();

Alternatively you can create the struct variable by using new keyword. In this case if you are not passing x and y values, it will default values of that type; that is 0. Because you invoke the structure’s default constructor. By definition, a default constructor takes any input parameters. The benefit of invoking the default constructor of a structure is that each piece of field data is automatically set to its default value. If you pass the values for x and y, it will display the addition of x and y.


This will take the default values for x and y as 0 and display the result as 0.


            Sum obj = new Sum();
            obj.Add();


This will display the addition of x and y


            Sum obj = new Sum();
            obj.x = 10;
            obj.y = 20;
            obj.Add();


Even you can create custom constructor for structure as shown below.

      public int x;
      public int y;
      public Sum(int X, int Y)
      {
            x = X;
            y = Y;
      }

 

                                                                                                         StructureExample.zip (20.77 kb)

Add comment

Loading

© Copyright 2018 www.techcognition.com | Sitemap