-1

I'm trying to understand what's going on with this line of code. It looks like this:

var adapter = (IObjectContextAdapter) db

where db is a database context within the entity framework.

Firstly, why are the parenthesis on the interface? If I take them off I have a compile error, so that tells me there is some type of semantics at play and those parenthesis are telling the computer to do something.

I'm assuming that db is implementing the interface, am I correct? Why are they writing the code like this if that is the case?

Christos
  • 53,228
  • 8
  • 76
  • 108
Aldmeri
  • 187
  • 1
  • 2
  • 9

2 Answers2

2

Firstly, why are the parenthesis on the interface?

The db is an object (from you post, we can't say what's the type of db). Using the parenthesis you cast this object to an object that implements this interface, IObjectContextAdapter.

I'm assuming that db is implementing the interface, am I correct?

This is correct.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • But I don't understand, why would we type it like that? If this variable db implements the interface already, why is it that we are doing this? – Aldmeri Jul 18 '15 at 22:55
  • Could you please show us where the variable called `adapter ` is used? – Christos Jul 18 '15 at 22:58
  • @Aldmeri If the variable `db` already implements `IObjectContextAdapter`, you don't really need to cast it. Maybe the programmer wanted `adapter` to be a reference specifically of type `IObjectContextAdapter`, and wasn't aware they could just change `var` to `IObjectContextAdapter` and the assignment would work. Or maybe they just hadn't had enough coffee. I don't know. – Asad Saeeduddin Jul 18 '15 at 23:04
1

The parenthesis are the C# explicit cast operator, so in and of themselves, they are not specifically related to interfaces.

One of the reasons why you would use a cast to a specific interface, like in your sample, is when you don't know the type of the object that you are given, but you do know that it implements a given interface. This would happen when you call code over which you don't have control.

The interface acts as a "contract" between you, the user, and the person who implemented the class of the object. You can be guaranteed that the object will implement the specified interface, and you can then call the methods and properties defined by the interface on this object.

Hope this helps.

EDIT:

Another reason why they would use a cast is if the class/object implements more than one interface, and they want to make sure that the IObjectContextAdapter methods are going to be called. This is referred to as Explicit Interface Implementation

Luc Morin
  • 5,302
  • 20
  • 39