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

  • Home
  • SEARCH
  • 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 7045851
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:34:49+00:00 2026-05-28T02:34:49+00:00

Similar threads that addresses this are possibly there on SO, but I do not

  • 0

Similar threads that addresses this are possibly there on SO, but I do not understand them 🙁

I have a scenario like this:

internal static void AddToListBox(ListBox lb, User usr)
{
    if (CanAddUser(lb, usr))
        lb.Items.Add(usr);
}

static bool CanAddUser(ListBox lb, User usr)
{
    foreach (User u in lb.Items)
    {
        if (u.Id == usr.Id)
            return false;
    }
    return true;
}

Now I have another exactly similar scenario like this:

internal static void AddToList(List<User> lstUser, User usr)
{
    if (CanAddUser(lstUser, usr))
        lstUser.Add(usr);
}

static bool CanAddUser(List<User> lstUser, User usr)
{
    foreach (User u in lstUser)
    {
        if (u.Id == usr.Id)
            return false;
    }
    return true;
}

Basically both set does the same thing. I was curious if I could make it one function, but this is only how it worked, which makes the code more verbose:

internal static void AddToList(IEnumerable enumerable, User usr)
{
    if (enumerable is ListBox.ObjectCollection)
    {
        if (CanAddUser(enumerable, usr))
            ((ListBox.ObjectCollection)enumerable).Add(usr);
    }
    else if (enumerable is List<User>)
    {
        if (CanAddUser(enumerable, usr))
            ((List<User>)enumerable).Add(usr);
    }
}

internal static bool CanAddUser(IEnumerable enumerable, User usr)
{
    foreach (User u in enumerable)
    {
        if (u.Id == usr.Id)
            return false;
    }
    return true;
}

As I said it works, but the if else block makes it look ugly and kills the idea of shortening the code. Could I be doing something like this:

internal static void AddToList(IEnumerable enumerable, User usr)
{
    if (CanAddUser(enumerable, usr))
        ((whatever the type is passed, just find it yourself)enumerable).Add(usr);
}

??

I tried

internal static void AddToList(IEnumerable enumerable, User usr)
{
    if (CanAddUser(enumerable, usr))
        ((enumerable.GetType()) / (typeof(enumerable))enumerable).Add(usr);
    //both which wont compile.
}

So how to go about this? Is it impossible to cast IEnumerable to an unknown type? Or would the solution be just too messy that I should drop the plan? Anything can be done if I know the passed IEnumerable will be only of type ListBox.ObjectCollection and List<User> other than the if else logic? Sorry for the lengthy piece, just needed to explain my requirement..

UPDATE: StriplingWarrior’s answer necessarily solves my problem, but I wonder how would be the object cast to its original type, if I’m to implement the last function. Possibly via Reflection or something. I will mark the solution to this as answer. Thanks @StriplingWarrior once again.

UPDATE 2:
To make it more clear, forget all what has been posted above. Suppose I have a function like below. Admonish() is an extension method I have defined on objects of type List<Naughty> and List<Obedient> separately. How will I be able to write just one Sanitize function and pass either List<Naughty or List<Obedient to it? Like this:

internal static void Sanitize(IEnumerable enumerable)
{
    enumerable.Admonish();
}

??

I know I can do this:

internal static void Sanitize(IEnumerable enumerable)
{
    if (enumarable is List<Naughty>)
        ((List<Naughty>)enumerable).Admonish();
    if (enumarable is List<Obedient>)
        ((List<Obedient>)enumerable).Admonish();
}

How will I be able to do it in one go, like this:

internal static void Sanitize(IEnumerable enumerable)
{
    ((Determine type here, but how??)enumerable).Admonish();
}

Hope question is clear. I’m not looking for a special case solution but a general solution to get the type at run time so that an object can be cast to its type !!

  • 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-05-28T02:34:50+00:00Added an answer on May 28, 2026 at 2:34 am

    Since ListBox.ObjectCollection implements the IList interface, you should be able to use that interface for both cases.

    internal static void AddToList(IList list, User usr)
    {
        if (!list.Cast<User>().Any(u => u.Id == user.Id))
            list.Add(usr);
    }
    

    The only reason this didn’t work for IEnumerable is because that interface doesn’t have an Add method.

    Response to Update 2

    This question is a lot more complicated than it appears at first glance, and the answer would depend on what your Admonish method does. Does it just iterate the list and perform something specific on each member of the list?

    public static void Admonish(this IEnumerable<Naughty> followers)
    {
        foreach(var follower in followers) { follower.Preach(); }
    }
    
    public static void Admonish(this IEnumerable<Obedient> followers)
    {
        foreach(var follower in followers) { follower.Preach(); }
    }
    

    If this is the case, you can just make both Naughty and Obedient implement a specific interface:

    public interface IFollower
    {
        void Preach();
    }
    
    public class Naughty : IFollower {...}
    public class Obedient : IFollower {...}
    
    public static void Admonish(this IEnumerable<IFollower> followers)
    {
        foreach(var follower in followers) { follower.Preach(); }
    }
    
    internal static void Sanitize(IEnumerable enumerable)
    {
        enumerable.Cast<IFollower>().Admonish();
    }
    

    On the other hand, if Admonish does something different depending on what type you’re looking at, that’s not so simple:

    public static void Admonish(this IEnumerable<Naughty> followers)
    {
        foreach(var follower in followers) { follower.Chastise(); }
    }
    
    public static void Admonish(this IEnumerable<Obedient> followers)
    {
        foreach(var follower in followers) { follower.Encourage(); }
    }
    

    In this case, the only way to automatically call the correct Admonish method is to use reflection to find and call it. As far as the .NET framework is concerned, there is no reason to believe that the two Admonish methods are in any way related, so you can’t just pretend that they’re the same method.

    If you’re willing make Admonish a non-static method, you might use the dynamic keyword to accomplish more or less what you’re trying to do, but it won’t work on extension methods:

    public class Admonisher
    {
        public void Admonish(IEnumerable<Naughty> followers)
        {
            foreach(var follower in followers) { follower.Chastise(); }
        }
    
        public void Admonish(IEnumerable<Obedient> followers)
        {
            foreach(var follower in followers) { follower.Encourage(); }
        }
    }
    
    internal static void Sanitize(dynamic enumerable)
    {
        dynamic admonisher = new Admonisher();
        admonisher.Admonish(enumerable);
    }
    

    But even this approach only works if the enumerable you pass in is backed by a generic IEnumerable<Naughty> or IEnumerable<Obedient>. If you pass it a ListBox.ObjectCollection, even the dynamic runtime framework won’t be able to figure out which Admonish method to call.

    Finding and calling the correct method via reflection

    Let me begin by saying reflection is usually not the best solution for problems like this. Reflection is slow, and it negates most of the advantages of compiled programming languages. But if you think that’s the way to go, here’s how you’d do it. Supposing your Admonish method signatures look like this:

    public static void Admonish(this IEnumerable<Naughty> followers)
    

    … and assuming you have a list whose actual implementation type implements IEnumerable<Naughty>:

    IList list = new List<Naughty>(); // List<Naughty> implements IEnumerable<Naughty>
    

    … you could find and call the method like this:

    var utilClass = typeof(Utility); // the class with your admonish methods
    var admonishMethod = 
        (from m in utilClass.GetMethods()
        where m.IsStatic && m.Name == "Admonish"
        let parameter = m.GetParameters()[0]
        where parameter.ParameterType.IsAssignableFrom(list.GetType())
        select m).Single();
    admonishMethod.Invoke(null, new[]{list});
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There are several similar threads Q1 or Q2 to this one, but not exactly.
I have seen similar threads on this QnA, but my specific scenario is as
I'm stumped. There are several threads out there that reference a similar problem, but
I know there are many similar threads out there pertaining to this but I
Is there a join()-like method for threads that have been executed through the ThreadPoolExecutor?
I know there are similar threads, and I have read them all. However none
There are a few other threads that are similar, but I can't seem to
I am aware there are some similar threads but I am still not sure
Similar to this thread, but not exactly: How To Cache Information In A Threadsafe
I've seen a lot of similar threads but none that actually address my particular

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.