1

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

  1. Declare Item as class instead of struct

  2. Convert public Item Item { get; set; } into public Item Item;

Can you explain why this behaviour occurs and why above "solutions" solve the issue ?

M.Y.Mnu
  • 718
  • 8
  • 22
willy
  • 155
  • 7
  • 1
    From [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/structs) - "Structs are value types and classes are reference types." – peeebeee Dec 21 '17 at 11:17
  • A class is an enhanced type of structure where they added features like methods. So the c# compile supports both structures and classes but uses different rules for handling the two different objects. You should not be using the same name for both the class Item and the property Item. So the correct solution is to use a lower case 'i' for item : public Item item { get; set; } – jdweng Dec 21 '17 at 11:20
  • 2
    @jdweng: did you test that - it still prints zero. – PaulF Dec 21 '17 at 11:24

2 Answers2

2

You shouldn't use mutable structs they can have strange behaviour. Changing struct value would have no benefit, because you'd be immediately change they copy.Struct are value types, so that's why your code doesn't work as expected because you have set property and every time when you change it you actually change copy not original value (structs are not reference type).

Potential solutions:

  1. Refactor property(Because of work with copy)
  2. Make struct as class
  3. Make your struct immutable (use readonly e.g. for more details see this topic)
NSKBpro
  • 373
  • 1
  • 14
0

i think this may same issue https://stackoverflow.com/a/1747702/1199090

also you can read detail here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/

yunus
  • 83
  • 2
  • 9