I met (for me) a strange difference between structures and interfaces in C #. Consider this interface and structure:
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 the Number as property, use the ChangeNumber method to change n to 2 and print the number using Log, instead it prints 0:
public class NumberContainer { public Number Number { get; set; } public NumberContainer() { this.Number = new Number(); this.Number.ChangeNumber(2); this.Number.Log();
After a while, I realized that when I call this.Number.ChangeNumber(2); , I actually create a new object (due to getter) and change it to 2. But then I changed the code a bit by changing the Number Property for the INumber property:
public class NumberContainer { public INumber Number { get; set; } public NumberContainer() { this.Number = new Number(); this.Number.ChangeNumber(2); this.Number.Log();
In this case, it prints 2! Why is this happening? Does the same principle of structures apply to an interface?
source share