Example of Implemeting interface in structure and in class

Dhirendra
Posted by in C# category on for Intermediate level | Points: 250 | Views : 7463 red flag

This article shows example of implementing interface into structure and how the interface types will be considered. weather value type or reference type even if it is implemented in structure value type..

Introduction

Structure type is value type and class type & interface type is reference type. In this article explains how to verify that the interface is reference type even if it is used in structure( structure is value type)

Whenever we implement the interface in structure and assign the instance of that structure to an interface variable then it becomes reference type, however when we access the structure instance object directly then it is accessed as value type.

Below is an example of this scenario.

class Program

{

static void Main(string[] args)

{

SampleStruct strucInst1 = new SampleStruct();

strucInst1.StructureData = "Default Value";

//assign structure instance to another structure instance

SampleStruct strucInst2 = strucInst1;

//Modify the structure data through the structure instance

strucInst2.StructureData = "Modified Value";

Console.WriteLine("Structure strucInst1 Initial value:- '" + strucInst1.StructureData + "'");

Console.WriteLine("Structure strucInst2 Modified value:- '" + strucInst2.StructureData + "'");

//Assign structure instance to an interface variable.

IInterface interfaceInst1 = strucInst1;

interfaceInst1.InterfaceData = "Defualt interface value";

IInterface interfaceInst2 = interfaceInst1;

interfaceInst2.InterfaceData = "Modified Interface value";

Console.WriteLine("Structure interfaceInst1 Initial value:- '" + interfaceInst1.InterfaceData + "'");

Console.WriteLine("Structure interfaceInst2 Modified value:- '" + interfaceInst2.InterfaceData + "'");

Console.Read();

}

}


interface IInterface

{

string InterfaceData { getset; }

}


struct SampleStruct : IInterface

{

public string StructureData { getset; }

string interfaceData;

public string InterfaceData

{

get

{

return interfaceData;

}

set

{

interfaceData = value;

}

}


}


The out put of the above code print outs the following

Conclusion


So this article explain that how to verify that the interface is reference type not value type even if it is used in structure.

Page copy protected against web site content infringement by Copyscape

About the Author

Dhirendra
Full Name: Dhirendra Patil
Member Level:
Member Status: Member
Member Since: 3/23/2010 2:39:20 PM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)