BipinR
BipinR

Reputation: 493

Unable to assign a value to a property inside a struct without using new keyword

I'm unable to assign a value to a property inside a struct without using a new keyword to initialize the struct. If I try to assign a value to the property I get the below error. But I can assign a value to the public variable or call a method inside the struct without a new keyword. I'm trying to find a reason for this behavior. Please help.

Error: Use of unassigned local variable 'pd2'

struct P
        {
            public int i;
            public int j;
            public string e;
            public string Name { get; set; }

            public void Showi()
            {
                Console.WriteLine(string.Format("Display i:{0}",this.i));
            }
        }
static void Main(string[] args)
        {
            P pd2;
            pd2.i = 1;
            pd2.j = 1;
            pd2.e = "test";
            pd2.Name = "abc"; //This is a property, shows error here
         }

Upvotes: 1

Views: 618

Answers (1)

Servy
Servy

Reputation: 203822

call a method inside the struct without a new keyword

You can only call a method on the struct if you have ensured that every field is initialized (which results in the entire struct being initialized). If you haven't fully initialized very field, then you can't perform any other operations on it, as the error message you're getting is telling you. You'll need to initialize all of the fields before you're able to use that property setter, such as by calling the default constructor.

Upvotes: 2

Related Questions