472,356 Members | 1,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,356 software developers and data experts.

Explicit implementation on value type leads to rather counter intuitivebehavior...

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();
}
}
}


Aug 8 '06 #1
4 2284
Agree boxing can be a headache... personally that's partly why I only
generally use structs to define immutable entities... "keep it simple" and
all that...

IIRC, even in 2.0 /standard/ interface casting does involve boxing, however,
I understand (not 100% sure) that an interface contraint on a generic method
does /not/ box... a bit tricky to prove without looking at the IL, however
(since you'd need to use ref, and its unclear if it is simply unboxing
afterwards). I don't /think/ it boxes, though... unless (within the generic
method) you assign it to an interface of the same type as it already
supports!

Marc


Aug 8 '06 #2
Mathieu Cartoixa wrote:

<snip>
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 ?
Boxing is always involved when you cast a value type to object,
ValueType or an interface type.
>From 13.1.5 (ECMA spec):
<quote>
A boxing conversion permits any value-type to be implicitly converted
to the type object or to any interface-type implemented by the
value-type. Boxing a value of a value-type consists of allocating an
object instance and copying the value-type value into that instance.
</quote>

As Marc said, this suggests an inappropriate use of structs.

Jon

Aug 8 '06 #3
For ref, I've just looked at some IL, and it appears to bear this out;
cast to interface = box
generic constraint = not boxed

This only really makes a difference in terms of avoiding the performance
implications of boxing / unboxing - you've still got the headache of
value-type semantics - i.e. the object being cloned as it passes between
different stacks... yup, I'll definitely stick to immutables ;-p

Marc
Aug 8 '06 #4
Jon Skeet [C# MVP] a écrit :
>
<snip>

From 13.1.5 (ECMA spec):
<quote>
A boxing conversion permits any value-type to be implicitly converted
to the type object or to any interface-type implemented by the
value-type. Boxing a value of a value-type consists of allocating an
object instance and copying the value-type value into that instance.
</quote>

As Marc said, this suggests an inappropriate use of structs.

Jon
Well, you know how it goes : I started with simple structures (similar
to SqlInt16, SqlInt32...), and one day I realized that they would have
to be "internally mutable", i.e. mutable only inside the library I was
building. I (wrongly) figured that explicit implementation of an
interface would do the trick.
As for the C# Reference (MSDN), it just states that "Structs can
implement an interface but they cannot inherit from another struct." and
that "A struct can implement interfaces."...

Anyway, thanks for your lights.

Mathieu
Aug 9 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: David Mertz, Ph.D. | last post by:
I decided to write a pure Python hashcash implementation. I have seen David McNab's Python implementation. Unfortunately, as near as I can tell (which is supported on the hashcash mailing list...
6
by: MPowell | last post by:
Lets suppose the return value on new_command is MSG2_STATUS My intent then is to memcpy the data via the call to CMDHolder and have a function that'll retrieve a copy of the 'stored' data. The...
1
by: Stub | last post by:
Docs says that "The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction." I put up code of three cases...
4
by: Ken Tough | last post by:
Seems like a simple thing to find out, but I'm struggling. I have googled, but everything I find is about implicit conversion, not explicit. Is this implementation-specific, or does ANSI/ISO...
12
by: Steve W. | last post by:
I just read the section (and did the exercise) in the C# Step by Step book that covers Explict Interface Implementation (where you specify in the method implementation the specific interface that...
31
by: Michael C | last post by:
If a class inherits from another class, say Form inherits from control, then I can assign the Form to a variable of type Control without needing an explicit conversion, eg Form1 f = new Form1();...
2
by: COLIN JACK | last post by:
Hi All, I've got a situation where I'm implementing an interface (BaseInterface in example below) and I want to use explicity interface implementation of an event so that I can add type safety. ...
3
by: Steven T. Hatton | last post by:
Has anybody here used explicit instantiation of templates? Has it worked well? Are there any issues to be aware of? -- NOUN:1. Money or property bequeathed to another by will. 2. Something...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
1
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.