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.

Example:

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.stnumber="M001";

st.stname = "Dara Yuk";

st.stsex="M";

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.

Example:

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

student st=new student("s001","Dara Yuk","M"); //create object
Console.Write("{0}\t{1}\t{2}",st.stnumber,st.name,st.sex);

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.





Comments

Name:
Comment:
Enter the text:
CAPTCHA image

....................................................................................................................Home | Forum | About | Contact
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.
Copyright @ 2011-2013 worldbestlearningcenter. All Rights Reserved.
Home Programming Web DB & App Questions Exercises Tips Programs FAQs Download About
Computer-Wbest
Popular Pages
You might like