larryq
larryq

Reputation: 16299

Attached an anonymous type to an object; how to retrieve it?

I'm playing with the .NET BackgroundWorker class. As part of its functionality you can call a method named ReportProgress that allows you to pass in the percentage your background task has completed, along with an optional user parameter.

Eventually ReportProgress calls an event handler and the optional user parameter becomes the "UserState" member of the event argument.

Here's a quick sample in case I'm not being clear:

BackgroundProcess.ReportProgress(100, new{title="complete"});
/*****later on, this method is called******/
private void myEventHandler(object sender, RunWorkerCompletedEventArgs e)
{
   //e.UserState is my anonymous type defined in the call to ReportProgress(...)
}

My question is, how can I access the "title" value in my anonymous type? I assume I'll need to use reflection but so far I'm not having great luck.

Upvotes: 2

Views: 256

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

Don't use anonymous objects. They are scoped only to the current method. Once you leave the scope of the current method in which they are defined accessing them becomes a PITA. So define a simple class and then cast to this class:

BackgroundProcess.ReportProgress(100, new MyClass { Title = "complete" });

and then:

private void myEventHandler(object sender, RunWorkerCompletedEventArgs e)
{
   var title = ((MyClass)e.UserState).Title;
}

Upvotes: 3

Aliostad
Aliostad

Reputation: 81660

You cannot and there is no reason why you should not create a class to pass the values.

On possibility is casting to dynamic and then getting the property but I do not recommend it.

Upvotes: 1

Eric Mickelsen
Eric Mickelsen

Reputation: 10377

If you are using C# 4.0:

dynamic o = e.UserState;
o.title;

You can use reflection, but it would be big, slow and ugly. A named type would be more sensible.

Upvotes: 4

Related Questions