C# tutorial-structure

C# structure

A structure is a collection of variables. For instance, if you have a student structure then you will group the student number, student name, and sex together.

To create a structure, you must use struct keyword followed by the name of the structure. Variables of the structure must be put in curly brackets. In the example below, we create a structure named student containing stnumber, stname, and stsex variables.


struct student


            public  string stnumber;

            public string stname;

            public string  stsex;



You can use the student structure as shown below:

student st=new student();


st.stname = "Dara Yuk";


Console.WriteLine("{0}\t{1}\t{2}", st.stnumber,st.stname,st.stsex);

Constructors of C# structure

In c#, a structure can have constructors. A constructor is a special member of the structure. It can be used to initialize variables of the structure when its object is created. The name of constructor must be the same as the name of structure. The constructor called automatically when the keyword "new" is used to create the objects of the structure.


struct student
    public string stnumber;
    public string stname;
    public string stsex;
    public student(string id,string name,string sex){ //constructor

student st=new student("s001","Dara Yuk","M"); //create object

Note: a structure in C# can have other members such as methods, properties, and events. However, if you have these kinds of things in your program, you should consider using class instead.


Sam comment


Wow it's good article, I jst try to sort this post at following url http://bit.ly/1slL7Fu


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.