Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast to an object to a type when type is known during runtime?

Tags:

c#

.net

wcf

I have a statement something like this: MyClass myClass = report.DataSource as MyClass

During runtime, the type of the DataSource is MyClass but it's in a different namespace than the current running project. That's because two projects are creating the same classes from the same service reference. DataSource points to one namespace and the MyClass cast is from a different namesapce. (it's complicated to explain how this occured)

During runtime, how do I use the type returned from report.DataSource.GetType() (returns MyClass from another namespace) and use it as type cast instead of 'MyClass' which is in the namespace which I don't want?

(I hope I've explained it clearly. My brain is foggy now!)

like image 531
Tony_Henrich Avatar asked Oct 22 '22 03:10

Tony_Henrich


1 Answers

Unfortunately, it's not just that its the "same class in a different namespace"... basically, you have 2 classes. They are completely different classes, because of the auto generated code.

As far as the .Net Runtime is concerned, they might as well be as different as "int" and "string". They probably even hail from different assemblies.

I've had a similar issue as well - and at this point, probably the easiest thing you can do is make your own generic converter method that will read the public properties from the one type, and populate them on the another type.

This can be done because you PROMISE that the two classes look identical :)

like image 159
Timothy Khouri Avatar answered Nov 01 '22 07:11

Timothy Khouri