Wednesday, February 17, 2016

What is structure in c#?



In C sharp Structure are the light weight classes and also value type, it contains fields, methods, constants, constructor, indexer.
Some key points of structure are given below:
Structure does not inherited
Not protected modifier is used
We cannot create default constructor in structure
With new keyword and without new structure is used while in class new is necessary
Instance field initializer is not possible in the structure
The example of the structure is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    struct mystruct
    {
       public  int x, y;
        public mystruct(int i, int j)
        {
            x = i;
            y = j;
        }
    }
}


Code on Button click:
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mystruct obj = new mystruct();
            obj.x = 1;
            obj.y = 2;
            MessageBox.Show(obj.x.ToString());
            MessageBox.Show(obj.y.ToString());
           
        }
    }
}

Output :
1
2





1 comment: