I came along an (according to me) strange difference between structs and interfaces in C#. Consider this interface and struct:
public interface INumber
{
void ChangeNumber(int n);
void Log();
}
public struct Number : INumber
{
private int n;
public void ChangeNumber(int n)
{
this.n = n;
}
public void Log()
{
Console.WriteLine(this.n);
}
}
When I create a new class with a Number as property, use the ChangeNumber method to change n to 2 and print the number by using Log, it prints 0 instead:
public class NumberContainer
{
public Number Number { get; set; }
public NumberContainer()
{
this.Number = new Number();
this.Number.ChangeNumber(2);
this.Number.Log(); //prints 0...
}
}
After a while I realised it was because when I call this.Number.ChangeNumber(2);
, I actually create a new object (because of the getter) and change that number to 2. But then I changed a little bit of the code by changing the Number property to an INumber property:
public class NumberContainer
{
public INumber Number { get; set; }
public NumberContainer()
{
this.Number = new Number();
this.Number.ChangeNumber(2);
this.Number.Log(); //prints 2!
}
}
In this case, it prints 2! Why is this happening? Doesn't the same principal of structs apply to the interface?