Groups | Blog | Home
all groups > c# > april 2006 >

c# : Interface casting required question



Rene
4/9/2006 11:42:27 PM
Supposed that a class "MyTestClass" implement interface "IMyInterface" (not
explicitly).

Now suppose that I make an instantiate of "MyTestClass" and then use this
instance to pass it to a function with an argument that requires
"IMyInterface" such as:

private void SomeFunction(IMyInterface xyz) {.}

My question is, will this function require a cast to "IMyInterface"? For
example, if I was to do this following, would this require a cast?

MyTestClass experiment = new MyTestClass();
SomeFunction(experiment); // Cast because argument is type "IMyInterface"???

Or does the compiler knows that the instance of the object implement the
interface and it ends up implementing the code the exact same way as if the
"SomeFunction" would have the argument of type "MyTestClass" instead of
"IMyInterface"?

Thank you.

Jon Skeet [C# MVP]
4/10/2006 12:00:00 AM
[quoted text, click to view]

No.

[quoted text, click to view]

There's an implicit conversion from a type which implements an
interface to that interface, so the compiler knows it can call that
method.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button