tags:

views:

105

answers:

2

Hello, i just have a little design question.

If i got this code

public Interface Test
{
  void Xyz();

}


public class1 : WebControl , Test
{
 public void XyZ()
 {
  // do someting
 }

 public OnLoad()
 {
   ((Test)this).Xyz();

// or   

   Test ctrl = this as Test;
   ctrl.Xyz();

// or

   Xyz();

 }

}

Did the code will have a performance difference ? I think Xyz() direct call will be faster but i am not sure ((Test)this).Xyz() will have a difference with the direct call.

What are your opinion about that, or reference documentation.

Thanks

ps : I just whant have the difference performance, no answer with ... why you want to cast or specify the interface. I know i could just call directly my method

+2  A: 

Call the method directly, there is no need to cast the this reference to the interface type as the implementation of the method is still in the current class. If you cast the class to the interface type you are adding unnecessary indirection to get at a method that you have available to you.

I don't think there would be a huge performance difference (as Jon points out, the JIT will most likely remove all casting as it is unnecessary) but for readability's sake just call the method directly.

Andrew Hare
+7  A: 

I would hope that the compiler would remove both the cast and the "as" given that it can guarantee they will both succeed... and if that doesn't, the JIT may well do so. You would need the cast or as operator if you used explicit interface implementation, mind you. In that case I'd use a cast: I personally only use as if it's feasible for the value to not be of the right type (in a situation other than a bug).

Ultimately any performance difference will be insignificant, but for readability's sake I'd just do without the cast where possible.

Jon Skeet
+1 For mentioning JIT optimizations.
Andrew Hare
Thanks for the answer.
Cédric Boivin