-1

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; }
}
Garvit
  • 55
  • 1
  • 8
  • You need to initialize the object StructA structObj = new StructA(); As for the why's of the errors, I'm sure someone will explain that better than I would – Innat3 Oct 18 '16 at 13:11

2 Answers2

0

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.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • 1
    After reading your answer i got another doubt ie if properties are converted to methods? So i googled it and msdn has cleared my doubt. It says "Properties are actually special methods called accessors.". So i guess answer is the correct reason why compiler shows two different errors. Thanks Jeroen. – Garvit Oct 18 '16 at 13:27
0

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().

Niraj
  • 775
  • 7
  • 20