Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

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.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9018367
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T04:30:33+00:00 2026-06-16T04:30:33+00:00

I have a List<object> which is a collection of various type of objects. I

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T04:30:34+00:00Added an answer on June 16, 2026 at 4:30 am

    If you need to use a string as parameter you can’t rely on OfType<T>() extension method. Fortunately it’s easy to emulate:

    public IEnumerable<object> OfType(this List<object> list, string typeName)
    {
        return list.Where(x => x != null && x.GetType().Name == typeName);
    }
    

    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 the IConvertible interface) are little bit more tricky. For simple (implicit) casts (like with inheritance and interfaces) you can use this:

    public IEnumerable<object> OfType(this List<object> list, string typeName)
    {
        Type type = Type.GetType(typeName);
        return list.Where(x => x != null && type.IsAssignableFrom(x.GetType()));
    }
    

    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 CastExtensions class (or update code if you don’t) then declare this small enum for its options:

    [Flags]
    public enum CastOptions
    {
        None = 0,
        ExcludeNulls = 1,
        UseConversions = 2
    }
    

    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).

    public static IEnumerable<object> OfType(this List<object> list, 
                                             string typeName, CastOptions options)
    {
        Type type = Type.GetType(typeName);
    
        foreach (var obj in list)
        {
            if (Object.ReferenceEquals(obj, null))
            {
                if (options.HasFlag(CastOptions.ExcludeNulls))
                    continue;
    
                yield return obj;
            }
    
            var objectType = obj.GetType();
    
            // Derived type?
            if (type.IsAssignableFrom(objectType))
                yield return obj;
    
            // Should we try to convert?
            if (!options.HasFlag(CastOptions.UseConversions))
                continue;
    
            // Castable?
            object convertedValue = null;
    
            try
            {
                var method = typeof(CastExtensions)
                    .GetMethod("Cast", BindingFlags.Static|BindingFlags.NonPublic)
                    .MakeGenericMethod(type);
    
                convertedValue = method.Invoke(null, new object[] { obj });
            }
            catch (InvalidCastException)
            {
                // No implicit/explicit conversion operators
            }
    
            if (convertedValue != null)
                yield return convertedValue;
    
            // Convertible?
            if (options.HasFlag(CastOptions.UseConversions))
            {
                try
                {
                    IConvertible convertible = obj as IConvertible;
                    if (convertible != null)
                        convertible.ToType(type, CultureInfo.CurrentCulture);
                }
                catch (Exception)
                {
                    // Exact exception depends on the source object type
                }
            }
        }
    }
    

    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:

    private static T Cast<T>(object obj)
    {
        return (T)obj;
    }
    

    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:

    int a = 1;
    float a = Cast<float>(a); // Run-time error
    

    This is because (object)1 cannot be converted to anything else than int (this is true for all boxed value types). If you’re using C# 4.0 you should change object for parameter obj to dynamic and everything will work as expected (for all types).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an Object X which contains a list of Objects X. I do
I have an object of type list from which I wish to use to
I have a list of objects, of which I cannot know the type of
I have a List<> collection which contains a bunch of images. Each object within
I have a list which contains a collection of objects. How can I search
I have a strongly-typed view bound to an object which contains a Collection (list)
I have a Generic List object which hold below table as its own value.
I have a list of an object which need to be sorted depending on
I have an object which is contained within a List<>, I need to remove
I have an asp.net page which is returning a list of object as a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.