Difference Between Value Type And Reference Type

Value Type in C#

The value type-based objects directly contain the value. Here there is no need to create an instance with values.

The value type variables are.

  1. struct
  2. enum

Example

using System;
namespace ConsoleApplication1
{
    class Program
    {
        struct Point
        {
            private int x, y;

            public Point(int x, int y)
            {
                this.x = x;
                Console.WriteLine(x);
                Console.ReadLine();
                this.y = y;
            }
            public int X
            {
                get { return x; }
                set { x = value; }
            }
            public int Y
            {
                get { return y; }
                set { y = 3; }
            }
        }
        static void Main(string[] args)
        {
            Point p = new Point(2, 3);
            p.X = 9;
            int x = p

In the above program, we have used structure variables like.

Point p = new Point(2, 3);

Here we are passing value to x and y. So, we call this a value type.

Reference Type in C#

The reference type variables will create only instances but pass any values.

Example

using System;
using System.Windows.Forms;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Application.Run(new frm());
        }
    }
    class frm : Form
    {
        public frm()
        {
            Button b = new Button();
            this.Controls.Add(b);
            b.Click += new EventHandler(b_Click);
        }

        void b_Click(object sender, EventArgs e)
        {
            frm1 f = new frm1();
            f.Show();
        }
    }
    class frm1 : Form
    {
    }
}

In the above program, we created an instance to open another form, and other form variables were accessed only after creating an instance.

Up Next
    Ebook Download
    View all
    Learn
    View all