structs implementing interfaces, (un)boxing and performance

A

Andreas Mueller

Hi,

I have a struct that implements an interface:

interface IMyInterface
{
void DoIt();
}
public struct MyStruct : IMyInterface
{
void IMyInterface.DoIt(){}
}

and somehwre else I have a method, that takes the interface :

public void UseIt(IMyInterface myi){}

As my implementation of the interface does not need any data, I decided
to make it a struct, as this should be more efficient.

But what is happening now when I pass a struct into the function that
takes the interface:

MyStruct s = new MyStruct();
UseIt(s);

Will the struct be "boxed" before it is passed or is there another
mechanism in place?

Thanks in advance,
Andy
 
A

Andreas Huber

Andreas said:
Hi,

I have a struct that implements an interface:

interface IMyInterface
{
void DoIt();
}
public struct MyStruct : IMyInterface
{
void IMyInterface.DoIt(){}
}

and somehwre else I have a method, that takes the interface :

public void UseIt(IMyInterface myi){}

As my implementation of the interface does not need any data, I
decided to make it a struct, as this should be more efficient.

But what is happening now when I pass a struct into the function that
takes the interface:

MyStruct s = new MyStruct();
UseIt(s);

Will the struct be "boxed" before it is passed or is there another
mechanism in place?

Yes the struct will definitely be boxed, there's no way around that. When
you create types that are often accessed through interfaces, you're probably
better off with a class. However, this hugely depends on how exactly you'll
be using the type...

HTH,

Andreas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top