Hi,
I have been annoyed in one of my recent projects with a problem related
to the explicit implementation of an interface on a value type. I will
take an example to show the problem.
Say we have this simple interface :
interface IInitializable
{
void Init();
}
Let us implement it explicitly in a value type :
struct Struct:
IInitializable
{
public bool Initialized;
void IInitializable.Init()
{
Initialized=true;
}
}
Now if you create a new Struct :
Struct s=new Struct();
You can check that s.Initialized is false. Try to call the Init method
(you have to cast the instance to IInitializable due to the explicit
implementation) :
((IInitializable)s).Init();
Intuitively, you would expect s.Initialized to be true, but in fact it
is still false !
This is explainable, as I figure that there must be some boxing
occuring during the cast, but I found this quite disturbing... I don't
remember having read anything about boxing in casts, and I find this
"feature" quite dangerous. What do you think ?
Mathieu
PS : Here is my complete sample code
using System;
namespace TestValueType
{
interface IInitializable
{
void Init();
}
struct Struct:
IInitializable
{
public bool Initialized;
void IInitializable.Init()
{
Initialized=true;
Console.Out.WriteLine("Struct.Init()");
}
}
class Class:
IInitializable
{
public bool Initialized;
void IInitializable.Init()
{
Initialized=true;
Console.Out.WriteLine("Class.Init()");
}
[STAThread]
static void Main(string[] args)
{
Class c=new Class();
Console.Out.WriteLine("Class.Initialized={0}", c.Initialized);
((IInitializable)c).Init();
Console.Out.WriteLine("Class.Initialized={0}", c.Initialized);
Console.Out.WriteLine();
Struct s=new Struct();
Console.Out.WriteLine("Struct.Initialized={0}", s.Initialized);
((IInitializable)s).Init();
Console.Out.WriteLine("Struct.Initialized={0}", s.Initialized);
Console.Out.WriteLine();
Console.ReadLine();
}
}
}