I have a List<object> which is a collection of various type of objects.
I am writing a helper method which will return a specific type of object. The helper method will accept type name as string parameter.
Note: I am using 3.5 framework.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you need to use a string as parameter you can’t rely on
OfType<T>()extension method. Fortunately it’s easy to emulate:As pointed out by @ChrisSinclair in the comment this solution does not manage conversions, casts and inheritance/interfaces. Casts (because of user defined conversion operators) and conversions (because of
TypeConverters and theIConvertibleinterface) are little bit more tricky. For simple (implicit) casts (like with inheritance and interfaces) you can use this:How to perform conversions (even with CUSTOM CONVERSION OPERATORS) at run-time
I found I needed something like the code I posted in this answer but I had to extend it a little bit, here a better implementation that takes care of custom casts and conversions.
Put everything inside a
CastExtensionsclass (or update code if you don’t) then declare this smallenumfor its options:The problem is that C# in general is a statically typed language, it means that almost everything (about types) must be known at compile time (then to perform a cast you have to know type your want to cast to at compile time). This function handles simple cases (like derivation) and more complex ones (interfaces, custom conversion operators – casts – and conversions – when required).
Note that conversion may be or not equivalent to a cast, actually it depends on
the implementation and the exact types involved in the operation (that’s why you
can enable or disable this feature through options).
This is a small helper function needed for cast at run-time:
We may emit this code at run-time (I suppose even using expressions but I didn’t try) but a small helper method will generate exactly the code we need (conversion from an object to a generic known at run-time type). Note that this cast function doesn’t work as expected for value types, for example:
This is because
(object)1cannot be converted to anything else thanint(this is true for all boxed value types). If you’re using C# 4.0 you should changeobjectfor parameterobjtodynamicand everything will work as expected (for all types).