Reputation: 57
I understand struct is value type. But I do not understand why it behave like this? Is it because i didn't treat it as immutable? or is it has something to do with the auto property?
using System;
namespace StructQuestion
{
class Program
{
static StructType structAsProperty { get; set; }
static StructType structAsField;
static void Main(string[] args)
{
structAsProperty.InjectValue("structAsProperty");
structAsField.InjectValue("structAsField");
//debugger says structAsProperty.GetValue() is null
Console.WriteLine(structAsProperty.GetValue());
Console.WriteLine(structAsField.GetValue());
Console.ReadLine();
}
}
public struct StructType
{
private string value;
public void InjectValue(string _value)
{
value = _value;
}
public string GetValue()
{
return value;
}
}
}
Upvotes: 2
Views: 90
Reputation: 416131
Let's look at what happens in this statement:
structAsProperty.InjectValue("structAsProperty");
We don't have to go far. The very first thing that must happen is to resolve the structAsProperty
part of the statement. The key here is understanding the compiler re-writes property get
and set
sections as a method calls behind the scenes.
So what we really have here is a call to a method that returns our struct value. I say "value" here rather than "object" because structs are value types. With value types, passing to or returning from a method results in a copy of the value.
Now we know enough to understand what happened. We are calling InjectValue()
on a copy of the property struct, not the instance in the property itself. Next we modify this copy via it's InjectValue()
method... and then promptly forget the copy ever existed.
You can fix it like this:
var prop = structAsProperty; //now we have a variable to keep the result of the implicit get accessor method
prop.InjectValue("structAsProperty");
structAsProperty = prop;
Upvotes: 2