Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# assigning value to property of struct error

Tags:

c#

structure

I have the following code (simplified), a structure and a class.

public struct pBook
{
    private int testID;

    public string request;
    public string response;
    public Int32 status;
    public int test_id
    {
        get
        {
            return testID;
        }
        set
        {
            testID = value;
        }
    }
};

public class TestClass
{
    public static void Main(string[] args)
    {
        pBook Book1;
        pBook Book2;

        Book1.request = "a";
        Book2.response = "b";
        Book2.status = 201;
        Book2.test_id = 0;  //this doesn't work, why?
    }
}

At the statement

Book2.test_id = 0;

I get the error

use of unassigned local variable 'Book2'

Any ideas how to correct?

like image 566
Nick Avatar asked Mar 04 '23 01:03

Nick


1 Answers

In "definite assignment", a struct requires all fields to be assigned before methods can be called, and properties (even property setters) are methods. A lazy fix is simply:

var Book2 = default(pBook);
// the rest unchanged

which fools definite assignment by explicitly setting everything to zero. However! IMO the real fix here is "no mutable structs". Mutable structs will hurt you. I would suggest:

var Book2 = new pBook("a", "b", 201, 0);

with (note: this uses recent C# syntax; for older C# compilers, you may need some tweaks):

public readonly struct Book
{
    public Book(string request, string response, int status, int testId)
    {
        Request = request;
        Response = response;
        Status = status;
        TestId = testId;
    }
    public string Request { get; }
    public string Response { get; }
    public int Status { get; }
    public int TestId { get; }
};
like image 95
Marc Gravell Avatar answered Mar 13 '23 04:03

Marc Gravell