I've got this subclass implementing my Interface and there are no errors in terms of satisfying the contract. However when I try to set the current session in the sub class's constructor I get this compile-time error when it tries to compare the variable type with the returned type of GetCurrentSession():
"Cannot convert source type IAPISession to target type FacebookSession"
Ok why? Facebook is a IAPISession... right??? polymorphism at play is my thinking so it should be happy with this comparison. Not sure here.
public class FacebookSession : IAPISession
{
private FacebookSession currentSession;
private FacebookSession()
{
currentSession = GetCurrentSession();
}
...more code
public IAPISession GetCurrentSession()
{
// my logic is here...whatever that may be
}
... more code
}
Updated
here's my actual interface:
public interface IAPISession
{
#region Properties
int SessionID { get; }
string UserID { get; }
bool SessionHasExpired { get; }
DateTime ExpirationDate { get; }
void LogOut(); // expires the session & sets SessionHasExpired
#endregion Properties
#region Methods
IAPISession GetCurrentSession();
#endregion Methods
}
This interface will be utilized across any API wrapper projects of ours (e.g. FlickrSession, etc.)
Yes this needs an explicit cast. You are receiving a generic (interface) session, but you want to use specific (Facebook) methods/fields.
You might envisage a scenario where GetCurrentSession()
returns a different type of IAPISession
!
use currentSession =
(FacebookSession)
GetCurrentSession();
use a try
block around the cast to
catch this possibility. I assume your
code would get confused if it weren't
a type of FacebookSession
, so you
need to deal with that situation.
Just to clarify:
FacebookSession fbSess;
IAPISession genSess;
FacebookSession getFbSession() { ... return this; }
IAPISession getSession() { ... return this; }
genSess = getSession(); // legal
genSess = getFbSession(); // legal - implicit cast works as FacebookSession
// is always a kind of IAPISession
fbSess = getFbSession(); // legal
fbSess = getSession(); // ILLEGAL - not all IAPISession's will be
// kinds of FacebookSession
fbSess = (FacebookSession) getSession();
// legal, but might throw a class cast exception
// if it isn't a FacebookSession.
and likewise,
genSess = fbSess; // ok, implicit cast to generic type
fbSess = genSess; // ILLEGAL, it may not be a FacebookSession
fbSess = (FacebookSession) genSess;
// legal but can throw an exception
Although GetCurrentSession
might actually be returning a FacebookSession
, the return type is IAPISession
and there is no implicit cast from an interface to any class implementing that interface.
Either change the return type of the GetCurrentSession
method to FacebookSession
or change the currentSession
field type to IAPISession
(or both if it makes sense to do so).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With