structs implementing interfaces, (un)boxing and performance

  • Thread starter Thread starter Andreas Mueller
  • Start date Start date
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
 
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
 
Back
Top