Why does this value in the structure not change at all?

This is a very simple question that I consider. Can anyone explain why this code outputs 1000, not 1050

public class Program
    {
        public static void Main()
        {
            Bus b = new Bus(1000);
            ((Car)b).IncreaseVolume(50);
            Console.WriteLine(b.GetVolume());
        }
    }

    public interface Car
    {
        int GetVolume();
        void IncreaseVolume(int amount);
    }

    public struct Bus : Car
    {
        private int volume;

        public Bus(int volume)
        {
            this.volume = volume;
        }

        public int GetVolume()
        {
            return volume;
        }

        public void IncreaseVolume(int amount)
        {
            volume += amount;
        }
    }
}
+5
source share
3 answers

Casting a value of type ( struct) to an interface binds a value. Thus, you call the method in a boxed copy of the value, and not in the value itself.

+8
source

Value types ( struct) are passed by value, but interfaces are considered reference types (not value types). Let's get a look:

Bus b = new Bus(1000);

Now bcontains the value of a Buswith its volume equal to 1000.

Car c = (Car)b;

b ( ) Car. c .

c.IncreaseVolume(50);

IncreaseVolume, Car. . ( ).

void Car.IncreaseVolume(int amount)
{
    ((Bus)this).IncreaseVolume(amount);
}

:

public void IncreaseVolume(int amount)
{
    volume += amount;
}

. , b, . , 1000:

Console.WriteLine(b.GetVolume());

.

+1

, . , # , , ( , Object), , .

, , , , :

  • -, , `Object` ` ValueType`. , . , , . , "List.Enumerator", "IEnumerator" .
  • struct , , `ref` , . , , "", . , , , , , , .

In most cases, if someone needs an implementation of a mutating interface, the type in question should be a class. Mutable structs should, as a rule, allow mutation only by changing the base fields directly or using static methods that work with the instance passed in ref.

0
source

All Articles