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 ofIAPISession!use
currentSession =(FacebookSession)
GetCurrentSession();
use a
tryblock around the cast tocatch this possibility. I assume your
code would get confused if it weren’t
a type of
FacebookSession, so youneed to deal with that situation.
Addition
Just to clarify:
and likewise,