Difference between Struct and Class with the implementation of Interface

struct cannot participate in inheritance, it can implement an interface. We need to be careful doing this, though; type casting a struct to an interface implicitly boxes the struct, which incurs the overhead of boxing and unboxing, and also has an interesting side effect.

Sample Program
Interface Implementation

public interface IShape
{
 int Top
 {
  get;
  set;
 }
void Move(int newLocation);
}
//Interface is implemented in Struct

public struct StructShape : IShape
{
public int Top
{
 get;
 set;
}
 
public void Move(int newLocation)
{
Top = newLocation;
}
}
//Interface is implemented for Class
 
public class ClassShape : IShape
{public int Top
{get;
set;
}
 
public void Move(int newLocation)
{ Top = newLocation;
}
}
 
--------------------------
Because of boxing, StructShape and iShape refer to different memory locations. They now have different values because the processing is done on different entities. On the other hand, with the class, classShape and iClassShape refer to the same entity, and updates to one affect both. This is the expected behaviour for both cases. The unexpected behaviour with the struct can lead to subtle logic errors.


var shape = new StructShape();
shape.Top = 100;
var classShape = new ClassShape();
classShape.Top = 200;
IShape iShape = shape as IShape;
iShape.Move(150);
IShape iClassShape = classShape as IShape;
iClassShape.Move(175);

Console.WriteLine("Struct: " + shape.Top);
Console.WriteLine("iShape: " + iShape.Top);
Console.WriteLine("Class: " + classShape.Top);
Console.WriteLine("iClassShape: " + iClassShape.Top);

Console.Read();

This illustrates the importance of immutability for structs. An immutable object is one whose values cannot be modified after creation.

OutPut of the program

 
 

No comments:

Post a Comment