Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a struct in C# [duplicate]

I have some code to initialize a struct in C#:

namespace Practice
{
    public struct Point
    {
        public int _x;
        public int _y;

        public int X
        {
            get { return _x; }
            set { _x = value; }
        }

        public int Y
        {
            get { return _y; }
            set { _y = value; }
        }

        public Point(int x, int y)
        {
            _x = x;
            _y = y;
        }    
    }    

    class Practice
    {
        public static void Main()
        {
            Point p1;
            p1.X = 1;
            p1.Y = 2;
        }
    }
}

The above code gives a compiler error:

error CS0165: Use of unassigned local variable 'p1'

Why is this error being thrown?

like image 583
Vinod Avatar asked Oct 15 '10 14:10

Vinod


1 Answers

You can't use a property in a struct until it knows all the fields have been filled in.

For example, in your case this should compile:

Point p1;
p1._x = 1;
p1._y = 2;
int x = p1.X; // This is okay, now the fields have been assigned

Note how you don't have to explicitly call a constructor here... although in well-encapsulated structs you almost always would have to. The only reason you can get away with this is because your fields are public. Ick.

However, I would strongly advise you not to use a mutable struct anyway. If you really want a struct, make it immutable and pass the values into the constructor:

public struct Point
{
    private readonly int x;
    public int X { get { return x; } }

    private readonly int y;
    public int Y { get { return y; } }

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

...

Point p1 = new Point(1, 2);
like image 119
Jon Skeet Avatar answered Sep 30 '22 09:09

Jon Skeet