views:

121

answers:

4

Why does the following produce a compiler error:

public interface OwnSession : ISession { }

[...]
OwnSession s = SessionFactory.OpenSession(); // compiler error (in german unfortunately)
[...]

"SessionFactory" returns a "ISession" on "OpenSession()" (NHibernate)

+10  A: 

You should cast the result:

OwnSession s = (OwnSession) SessionFactory.OpenSession();

If OpenSession() returns an ISession type, it could be anything that implements ISession, so you have to tell the compiler you expected a OwnSession type (only if you are sure it will return that of course)

On the other hand, you could declare your variable as ISession, and continue working with that. Unless you want to use methods or properties from the OwnSession type which are not available in the ISession interface spec.

Philippe Leybaert
Adding to that: You should develop against interfaces, not implementations. This means you should use "ISession s = SessionFactory.OpenSession();" since the SessionFactory could return several different types of sessions (or you might later want to use another session type yourself)
dbemerlin
OwnSession is declared as an interface in the question (not starting with an I, but still..)
FOR
Thanks! Now it's crystal clear, i could not figure it out because i was only thinking about the rules of class-inheritance.
anton
+1  A: 

I'm going to guess because OwnSession could be a much larger/different interface than ISession?

Imagine if OwnSession inherited from ISession but also added another method signature.. then the ISession returned by the SessionFactory.OpenSession method would mot match the contract defined by OwnSession (or it could, but not necessarily, depending on the actual concrete type returned... the compiler doesn't know that)

FOR
Thanks! Now it's crystal clear, i could not figure it out because i was only thinking about the rules of class-inheritance.
anton
A: 

The SessionFactory.OpenSession call will return an object that implements the ISession interface, but your OwnInterface is more specific. Casting could be one way out of this, or work with ISession directly...

Martin Milan
Thanks! Now it's crystal clear, i could not figure it out because i was only thinking about the rules of class-inheritance.
anton
+5  A: 

The returned object is only "ISession" it is not an "OwnSession" (btw. you should prefix it with I: IOwnSession). Imagine you have a function returning a burger, you cannot cast it as a cheesburger because it might not be one...

Stefan Egli
+1 for the burger example. Now i'm hungry...
dbemerlin
Off the record, but the interface name IOwnSession looks quite funny to me, though it is the correct convention to do so, indeed :D.
Webleeuw
+1 hmmmmm burger!
Pharabus
Thanks! Now it's crystal clear, i could not figure it out because i was only thinking about the rules of class-inheritance.
anton