compiler showing different errors for unassigned struct object field and property

194 Views Asked by At

In the below code in line:1, the compiler shows error :"Use of possibly unassigned field 'IntField' " but for line: 2 the error is "Use of possibly unassigned local variable 'structObj' " . Why different error?

class Program
{
    static void Main(string[] args)
    {

        StructA structObj;

        Console.WriteLine(structObj.IntField); //Line :1
        Console.WriteLine(structObj.IntProperty); //Line :2            

        Console.ReadKey();
    }
}


struct StructA
{
    public int IntField;
    public int IntProperty { get; set; }
}
2

There are 2 best solutions below

1
Jeroen van Langen On BEST ANSWER

Because StructA is a struct and IntField is a field.

Try StructA structObj = new StructA() before you use it.

I think the reason of the difference between the errors is that the property is converted to methods. And calling a method on a not initialize object is not possible.

0
Niraj On

Here you need to call new() for structure because if the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.

so for intialization of value for property it must be

StructA structObj = new StructA();

You can try without use of new for only variable in structure but initialization is required so just assign value like

structObj.IntField= 1;

But for property you required new().