Click here to Skip to main content
15,921,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

When I am creating a object for a session, it was throwing me a run time error i.e.
C#
Unable to cast object of type 'System.Collections.Generic.List`1[RACS.Completion.Web.Private.Activity.Service]' to type 'RACS.Completion.Web.Private.Activity.Service'.

My code is like this:
C#
Service obj = new Service();

         obj = (RACS.Completion.Web.Private.Activity.Service)Session["obj"];

Can anyone help on this.


Regards,
Basha.s
Posted
Updated 27-Dec-11 22:45pm
v2

Replace:

Service obj = new Service();


With:

RACS.Completion.Web.Private.Activity.Service obj = new RACS.Completion.Web.Private.Activity.Service()
 
Share this answer
 
Try adding a set of brackets to specify the operator priority:
C#
Service obj = new Service();
obj = (RACS.Completion.Web.Private.Activity.Service)(Session["obj"]);

Alternatively, check that the Session["obj"] return value is a Service, as the error message implies it is a Session[] instead.

BTW: It is a bad idea to always create a new object to fill a variable when you construct it - particularly when you are going to replace it's content immediately. It wastes memory, and possibly other resources in the object constructor. Either leave it null, or create it when you do the initial assignment (from Session in your example)
 
Share this answer
 
Seems like you have
List<service></service>
in
Session["obj"]
.

It's better to try something like that:

C#
   if(Session["obj"]!=null)
   {
       var objList=Session["obj"] as List<racs.completion.web.private.activity.service>;
       var objRes=objRes!=null ? objList.FirstOrDefault() : new racs.completion.web.private.activity.service();
       if(objRest!=null) ..
   }
</racs.completion.web.private.activity.service>


After that you should think - why you have List<racs.completion.web.private.activity.service> in Session["obj"] and not RACS.Completion.Web.Private.Activity.Service, or you'll have new problems later.
 
Share this answer
 
v2
import namespace RACS.Completion.Web.Private.Activity.Service
and the use

Service obj=new Service();
problem fixed!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900