How to declare and use a simple struct (value type) in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication1
{
    public struct Point
    {
        public int X, Y;
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Point p1 = new Point();

                p1.X = 12;

                Point p2 = p1; // copy

                Console.WriteLine(p1.X); // 12
                Console.WriteLine(p2.X); //12

                p1.X = 30;
                Console.WriteLine(p1.X); // 30
                Console.WriteLine(p2.X); // 12
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
    
12
12
30
12
  
*/


answered Jun 25, 2014 by avibootz
edited Sep 5, 2015 by avibootz
0 votes
using System;

namespace ConsoleApplication1
{
    struct Point
    {
        private int px, py;

        public int x
        {
            get
            {
                return px;
            }
            set
            {
                px = value;
            }
        }
        public int y
        {
            get
            {
                return py;
            }
            set
            {
                py = value;
            }
        }
        public void Show()
        {
            Console.WriteLine("x: {0} y:{1}", px, py);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Point p = new Point();

                p.x = 20;
                p.y = 30;

                p.Show();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
    
x: 20 y:30
  
*/

 



answered Sep 5, 2015 by avibootz

Related questions

1 answer 124 views
124 views asked Apr 27, 2017 by avibootz
1 answer 159 views
3 answers 238 views
1 answer 131 views
1 answer 179 views
179 views asked Oct 7, 2014 by avibootz
1 answer 160 views
...