Background: in my website, a 3rd party HTTP Module builds a collection of objects in the HttpRuntime Cache. In my web application project, I need to examine these objects in the Cache and take various actions if an object with a particular property value is found.
So, I am looping through the cache collection, trying to cast each object to an instance of a local class (which is identical to the design of the 3rd party class).
(I know I could create a reference to the 3rd party assembly, but the assembly might not be installed, so I am try to create a more robust method).
However, the cast doesn’t work. ASP.NET knows that the original object originates from a different assembly. This is the exception:
[A]3rdParty.HttpModule.CachedRequest cannot be cast to
[B]3rdParty.HttpModule.CachedRequest. Type A originates from
‘3rdParty.HttpModule, Version=3.6.0.0, Culture=neutral,
PublicKeyToken=null’ in the context ‘Default’ at location
‘C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\61910352\63f5dc4f\assembly\dl3\710995cc\37f36a76_71e5cb01\3rdParty.HttpModule.dll’.
Type B originates from ‘MyCompany.MyWebsite, Version=1.4.0.1396,
Culture=neutral, PublicKeyToken=null’ in the context ‘Default’ at
location ‘C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary
ASP.NET
Files\root\61910352\63f5dc4f\assembly\dl3\8bfb9ba0\0c053836_8595cc01\MyCompany.MyWebsite.DLL’.
All I need to do is check the value of 1 string property in the object. Is there some (simple) way to do this? Even serializing the object to a string and parsing the string would be OK.
Thanks
.NET is strong-typed, so no, you can’t cast an object to something of a different type — even if the memory layout happens to be identical, .NET knows they’re different types.
To read a property of an object, without having a compile-type reference to its assembly, you need to use either Reflection, or
dynamic.dynamicis probably simpler.