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; }
}
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.