tags:

views:

46

answers:

2

Hi,

I am stuck with an InvalidCast Exception. I am calling a delegate to run some function. In the callback method of the delegate I am trying to get the return value of the function as shown below.

     public delegate SyncHelper.SyncPlan RunJobDelegate();

     public static void SyncJobCallback(IAsyncResult result)
    {

        RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState;
        SyncHelper.SyncPlan obj_Plan = runSyncJob.EndInvoke(result);

When RunJobDelegate runSyncJob = (RunJobDelegate)result.AsyncState; is called I am hitting an exception saying "Unable to cast object of type 'RunJobDelegate' to type 'RunJobDelegate'. "

Please help me with the solution if anyone has seen this before.

Divya.

+2  A: 

This sort of thing should only ocurr if you have two different RunJobDelegate types defined in your code. Make sure it isn't defined twice.

If that isn't the problem, please most more of the code (including the calling function) for us to examine.

John Fisher
Yes, You are right. I have declared the same type of delegate but in a different namespace in a different class. I have removed that and used the already existing one and my issue got resolved. But can you please tell me why that is an issue?
Muppa Divya
Thanks a lot for helping me out here :)
Muppa Divya
System.Data.Whatever is a totally different type than Your.Own.Namespace.Whatever. Having the same "last name" doesn't make them the same type. So, if you used the first type and tried to cast it to the second type, it would fail without a way to convert one to the other.
John Fisher
A: 

Did you check the type of result.AsyncState in the debugger?

also are you sure you want to use AsyncState and not AsyncDelegate?

Reference: http://msdn.microsoft.com/en-us/library/system.iasyncresult.asyncstate.aspx

Sandeep Singh Rawat