Search code examples
c#structpointdefinition

How to use fields of a struct without assigning a value to them first?


When defining a struct similar to System.Drawing.Point but with double instead of float: How to use X and Y without assigning a value to them first?

Example:

public struct PointD
{
    public double X;
    public double Y;
}

static void Main()
{
    PointD testPointD;
    double d = testPointD.X; // CS0170: Use of possibly unassigned field 'X'
    
    
    System.Drawing.Point point;

    // Here I can use X without defining it first.
    // So I guess the struct is doing something to make that work?
    // Edit: This also doesn't work, but Visual Studio did not underline it,
    // my fault!
    int i = point.X;
}

Solution

  • You are mistaken. The code you talked about woks just fine and there is no difference between PointF and your PointD:

        public Form1()
        {
            InitializeComponent();
    
            MyStruct ms = new MyStruct();
            this.Text = ms.p.X.ToString() + ms.d.X.ToString();
    
        }
    
        public struct PointD
        {
            public double X;
            public double Y;
        }
    
        public struct MyStruct
        {
            public PointF p;
            public PointD d;
        }
    

    The title of form1 shows "00" as expected.

    Edit:

    Maybe you are wondering why you get a complier error when you try to use a struct directly, that was not created but do not get an error when you use an un-created struct within a struct. Or one within a struct within a struct within a struct within a struct..

    Which should make it clear: The compiler doesn't follow these levels of nesting; it just flags things that are obvious to it, that is omissions within its direct scope.

    Granted, this can be a nuisance but all in all I'm glad to be warned instead of being allowed to forget initialization.