find and solve ||
Please wait.....

Structures in C# | C# when to use struct

In c#, a structure refers to a user-defined value type. It allows you to create new value-type objects that are similar to the built-in type objects, such as int, double and bool. A structure can contain constructors, fields ,methods and properties. One major difference between a structure and a class in c# is that a structure does not  support inheritance. By default ,all the members of a structure are private. If you do not assign a value to a  variable of a structure, a default value is automatically assigned to the variable.

 The struct keyword is used to declare a structure in c#. The basic syntax to define a structure is an follows:

 [access-modifier] struct <structure-name>





In the preceding syntax, 

struct is a keyword indicating that a structure is defined and 

structure-name is the name of the structure  begging defined.

1. Start Visual studio 2019 or other
2. Select File->New->Project from the menu bar.
3.Select Visual  C# console from the installed templates section in the left panel of the new project dialog box
4.Select Console Application from the middle panel to create a console application.
5.Enter the name of the application as SingleDimensionalArrays
6.Click the OK button to close the new Project dialog box and create the SingleDimensionalArrays
7.Add the code  as given below.

using System;

namespace Structures


   public struct X


            public int a,b,c;


public class Program


                public static void Main()



                                X X1= new X();




                                Console.WriteLine("Data of the X1 object:");

                                Console.WriteLine("A ="+ X1.a);

                                Console.WriteLine("B ="+ X1.b);

                                Console.WriteLine("C ="+X1.c);

                                X X2= new X();

                                Console.WriteLine("Data of the X2 object:");

                                Console.WriteLine("a = "+X2.a);

                                Console.WriteLine("b = "+X2.b);

                                Console.WriteLine("c = "+X2.c);





The first code snippet in the above shows the definition of a structures. The X structure contains three int type variables, a, b, c.In the second code snippet, we have created an object X1,of the X structure and assigned the values 1,2 and 3 to the a;b,c, variables of the X1 object, respectively. After that ,we have displayed the values of all the three variables,a,b and c, on the screen .Net, we have created another object,X2 pf the X strictire, and also displayed the values of all the three variables, a, b, and c, of the X1 object on the screen.


8.Press the F5 key on the keyboard to run the application.

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.


Report Response