Tutorial :C# Interface Inheritance (Basics)



Question:

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)


Solution:1

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)


Solution:2

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.


Solution:3

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


Solution:4

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »