Thursday, 17 September 2020

struct and interface : The confusion

The fact that, in C#, a value type like struct can implement an interface can be perplexing. It can lead to few misunderstanding unless you stick to one basic fact that struct is a value type. 

Let us create an interface for example.

public interface ITemp

{

        void M();

}

As it is allowed, we can have a struct that implements this interface.

public struct Temp2 : ITemp

{

        private int val;

        public void M()

        {

            val++;

            Console.WriteLine(val);

        }

}

So far, so good.

What happens if i pass a structure to a method that accepts parameter of type ITemp? Magic of boxing/unboxing takes place that ensures that struct is being passed as a reference. If you have a method that takes parameter of type struct Temp2, the value will be passed as value.

private static void Run(Temp2 temp)

{

            temp.M();

}

private static void Run2(ITemp temp)

{

            temp.M();

}

static void Main(string[] args)

{

var tempStruct = new Temp2();

tempStruct.M(); 

Run(tempStruct);

tempStruct.M();

Run2(tempStruct);

}

As you would have guessed, here is the output.

1

2

2

3

Hopefully, this clarifies the behavior of struct types that implement an interface.

No comments:

Post a Comment