Interface casting required question

R

Rene

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.
 
J

Jon Skeet [C# MVP]

Rene said:
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"???
No.

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"?

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

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