Cannot convert source type to target type
Solution 1
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 ofFacebookSession
, so you need to deal with that situation.
Addition
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
Solution 2
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).
Solution 3
You need the other way around:
public class FacebookSession : IAPISession
{
private IAPISession currentSession;
private FacebookSession()
{
currentSession = GetCurrentSession();
}
...more code
public FacebookSession GetCurrentSession()
{
// my logic is here...whatever that may be
}
... more code
}
If you want to use the specific implementation inside the class, then I would instantiate that class in the constructor. Then just return that instance in you GetCurrentSession class. For example:
public class FacebookSession : IAPISession
{
private FacebookSession currentSession;
private FacebookSession()
{
currentSession = new FacebookSession();
}
...more code
public IAPISession GetCurrentSession()
{
return currentSession;
}
... more code
}
And like Daniel mentions, this is getting close to the singleton pattern. See an implementation of it here. See the section under .NET Optimized Code
Related videos on Youtube

PositiveGuy
Updated on June 04, 2022Comments
-
PositiveGuy 12 months
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.)
-
PositiveGuy almost 13 yearsso just a quick comment. I see a lot of people here gunning for a Singleton because it's close to looking and functioning like a Singleton. But the usage of sessions in my case are a 1x1 relationship..user to unique session. A user will have many unique types of sessions (i.e. FacebookSession, PicasaSession, FlickrSession, and so on). So UserA will have several unique sessions depending on what API they've signed into via our code. When looking at this page from SwDevMan81, it reads " lets clients access its unique instance". Singletons are to be used for many to one resource situations
-
PositiveGuy almost 13 yearsA few days ago I thought I was just going to make these singletons but a good programmer friend of mine says in my case, it's the wrong use..you should not use a Singleton here due the fact that you're not sharing anything...that is a session is specific to one person, one thread. It's not that many threads "users" are using -one- specific session floating around. They each have multiple of their own based on what APIs they're logging into. As I look at that article by Gang of Four, it completely backs up what he stated, that it's many to one (singleton) relationships where it makes sense
-
PositiveGuy almost 13 yearsThanks all for your help..really appreciate it.
-
-
James Curran almost 13 yearsOf course you can cast from more generic to more specific. (In your example, you will get a run-time error, but if the typed matched, it would work fine).
-
Vilius Surblys almost 13 yearsIF
GetCurrentSession()
is defined on the interface, that would also need to return typeIAPISession
. -
SwDevMan81 almost 13 yearsIn which case it could just return IAPISession
-
PositiveGuy almost 13 yearsbut I thought due to polymorphism (an interface variable or lets say method param can take in any class which has implemented that interface into your method or set to your variables...just like an abstract class method param or variable type can take in any subclass which has implemented it). Isn't that a major purpose of using interfaces due to polymorphism??
-
PositiveGuy almost 13 years(Either change the return type of the GetCurrentSession method to FacebookSession) I can't because that doesn't satisfy my Interface contract. My Interface defines an abstact public IAPISession GetCurrentSession(); method becaue my intent is that this interface will be implemented by other API type sessions (Flickr, etc.) and reused across other api projects of ours. So that means if I make the return type IAPISession on that method, I should be able to return that subtype even though the return type is set to IAPISession I thought.
-
PositiveGuy almost 13 yearsSee this is where I don't see the benefit in this particular case of making that currentSession backing field an interface type instead of the subclass type itself. I mean I don't plan on utilizing that private variable in any other way...as to gain any polymorphism benefits from that. So is it really overkill to just make that local field type IAPISession just to satisfy the contract? I say no...like Sanjay says, this is a specific Sub type and I know the type. If I'm looking at the intent or that there is a good reason to do this other than "satisfying the error" please do explain to us.
-
Daniel Renshaw almost 13 yearsIt looks like you're part way towards the Singleton pattern. As it stands you have a GetCurrentSession() method that is not static so you'll need to create a sesson in order to get the current sesson! If a user of this class already has a reference to an instance of it, why would it ever need to call GetCurrentSession - it already has a session!
-
PositiveGuy almost 13 yearsso unlike abstract classes..whereas if I were to do something like this: MyMethod(SomeAbstractType type) where I could pass any subtype to this method that inherits SomeAbstractType, the same technique is not true to interfaces. Just because I have MyMethod(IAPISession session) doesn't mean I can pass in any subclass which has implemented IAPISession? So polymorphism works differently in the case of interfaces? Or am I just completely missing something beginner here that I've not taken into account with the concept of polymorphism and interfaces?
-
Daniel Renshaw almost 13 yearsPolymorphism allows you to treat all
FacebookSession
s "as an"IAPISession
but you can't do it the other way around since anIAPISesion
may actually be aTwitterSession
, for example. -
PositiveGuy almost 13 yearsgotcha, so that's why I was able to send in any subclass which implemented an abstract class in a method expecting that abstract class param type.
-
PositiveGuy almost 13 yearsDaniel, I tried to make that Interface method signature for GetCurrentSession static due to the very reasons you're stating but you can't declare a static method in an Interface, so...
-
PositiveGuy almost 13 yearsSo does that mean if you have a need for certain static members that you know EVERY wrapper you create in the future will need (i.e. a session will need a common way to get at it)...that if you expect to access that method statically though, then keep it out of the interface even though technically you think it should be in the contract? Because an interface doesn't support statics? So taht forces me to basically potentially keep out common members in some Interfaces I'm creating because I need to use them as static in the implementation?
-
Daniel Renshaw almost 13 yearsSee en.wikipedia.org/wiki/Singleton_pattern for info on the Singleton pattern (it has examples in C#). How you go about this depends on what you're trying to do. Will you have a "current session" of each session type or just one "current session" for thewhole application/user of just one session type (although you may not know exactly which it is due to polymorphsm)?
-
Sanjay Manohar almost 13 yearsOK I've answered this by adding an example
-
PositiveGuy almost 13 yearsI've looked and even used that pattern before. That's not what I want here for the session.
-
PositiveGuy almost 13 yearsthe user will have a possibility of one facebook, one flickr, one etc. session. It's a 1-to-1 relationship per session meaning user-to-session..not many users to one session(resource). I was told that Singletons should only be used to share functionality amongst for example lets say you have multiple threads..or in my case I have created Singletons for things like Certificates where everyone on the website would need an instance of this cert but there's only one cert out there that they need for whatever functionality we're providing them. In that case a Singleton is the way you go.
-
PositiveGuy almost 13 yearsSo again the Session is 1x1 here is always going to be a 1x1 - user-to-specific API session. One user may have logged into Flickr and Facebook thus those are 2 implementations so a FacebookSession and a FlickrSession for example will be created and floating around. I need to occassionally check to see if that object is still in memory...so all I have to do is just go and look for that object and see if it is available...no singleton needed. So every wrapper project we create (Flickr, Facebook, others) will be required to use this Interface pattern - they will all have those common members
-
PositiveGuy almost 13 yearssee my other replies in this thread to others why I don't want a Singleton here...
-
PositiveGuy almost 13 yearsI have used Singletons before but it's not what I want for this scenario which is a session...
-
PositiveGuy almost 13 yearswould you even need the as? I mean wouldn't it know by polymorphism that flickrSession is a IAPISession in your second line?
-
PositiveGuy almost 13 yearswell, I'd rather design by compile time errors...good practice and must makes sense and is why typed is "good"
-
PositiveGuy almost 13 yearsso yes it's "Will you have a "current session" of each session type". We already have a session for the overall app..this is for photo specific functionality on some of our pages.
-
PositiveGuy almost 13 yearsgot it was wrong interfaces are no different than abstract classes in the polymorphism relm...you can definitely swap out an interface for its subtype in lets say a method param as I talkd about in my last reply. Thanks.