Sunday, 28 January 2007

Structs Implementing an Interface

If a Struct is a ValueType and an Interface a ReferenceType and we know the contents of a variable is copied when copying a ValueType and the reference to the object is copied when copying a ReferenceType, what happens when we make a Struct implement an Interface?

public class MyClass



{



interface
ICustomValueType



{



int CustomVariable1 { get; set
; }



}







struct
MyValueType : ICustomValueType



{



public int
CustomVariable1



{



get { return
_customVariable1; }



set { _customVariable1 =
value; }



}
private int
_customVariable1;



}







public static void
Main()



{



// Direct reference to Value Type.




MyValueType valueType1 = new MyValueType();



valueType1.CustomVariable1
= 1
;







MyValueType valueType2
= new
MyValueType();



valueType2.CustomVariable1
= 2
;







Console.WriteLine(
"Value Type 1 = {0}"
, valueType1.CustomVariable1);



Console.WriteLine(
"Value Type 2 = {0}"
, valueType2.CustomVariable1);







valueType2
=
valueType1;



valueType1.CustomVariable1
= 5
;



Console.WriteLine(
"Value Type 1 = {0}"
, valueType1.CustomVariable1);



Console.WriteLine(
"Value Type 2 = {0}"
, valueType2.CustomVariable1);







// Reference to ICustomValueType.




ICustomValueType interfaceValueType1 = new MyValueType();



interfaceValueType1.CustomVariable1
= 1
;







ICustomValueType interfaceValueType2
= new
MyValueType();



interfaceValueType2.CustomVariable1
= 2
;







Console.WriteLine(
"Value Type 1 = {0}"
, interfaceValueType1.CustomVariable1);



Console.WriteLine(
"Value Type 2 = {0}"
, interfaceValueType2.CustomVariable1);







valueType2
=
valueType1;



valueType1.CustomVariable1
= 5
;



Console.WriteLine(
"Value Type 1 = {0}"
, valueType1.CustomVariable1);



Console.WriteLine(
"Value Type 2 = {0}"
, valueType2.CustomVariable1);



}



}
 
 
 
When interacting with the ValueType directly it acts like a ValueType and the variable is copied from the Stack.  When referencing the Interface the reference to the variable is copied and changing the value of one causes both instances to change. 

No comments: