I can't understand the C# semantic of this small piece of code.
using System;
namespace Test
{
struct Item
{
public int Value { get; set; }
public Item(int value)
{
Value = value;
}
public void Increment()
{
Value++;
}
}
class Bag
{
public Item Item { get; set; }
public Bag()
{
Item = new Item(0);
}
public void Increment()
{
Item.Increment();
}
}
class Program
{
static void Main(string[] args)
{
Bag bag = new Bag();
bag.Increment();
Console.WriteLine(bag.Item.Value);
Console.ReadKey();
}
}
}
Just reading the code I'd expect to read 1 as output in my console.
Unfortunely I don't get why console prints 0.
To fix the problem I can both
Declare
Item
asclass
instead ofstruct
Convert
public Item Item { get; set; }
intopublic Item Item;
Can you explain why this behaviour occurs and why above "solutions" solve the issue ?