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?
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; }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With