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 8320009
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T22:30:43+00:00 2026-06-08T22:30:43+00:00

I have a question about C# generics and delegate: First I describe the general

  • 0

I have a question about C# generics and delegate:

First I describe the general question—I want a collection of delegates, these delegates should have a similar form, for example, all my delegates should have the form:take two parameters of the same type, and return int. I guess the best way to model these delegates is by using generic delegate:

public delegate int MyFunctionDel <T> (T a, T b);

But how can I create a collection of MyFunctionDel with different type? I cannot declare this:

List<MyFunctionDel <T>> mylist; //Compile error: cannot find type T

And secondly, here is what I am actually trying to do. What I am trying to do could be solved by the above question. But you can give alternative solutions.

I wrote a collection-like structure: it can hold any type of data. But all the data in the structure should be of the same type. Unfortunately, this structure is not generic for some historical reason. This structure has a Compare method.

But now I need to provide customized comparers for some specific type. And the behavior I want is: the struture uses customized comparer if there is one for the type of data in it, otherwise uses the original Compare method. Here is my demo code:

/*
 *This piece of code demonstates my idea, but never works
 */

static class Program
{
    [STAThread]
    static void Main()
    {
        MyStructure s = new MyStructure ();

        //create a customized comparer using Comparison<T> generic delegate
        Comparison <string> myStirngComparer = (x , y)=> {
           return -x.CompareTo(y);
        };

        s.CustomizedComparers[typeof(string)] = myStirngComparer;

        System.Console.WriteLine (s.Compare("a" , "b")); //I am expecting the result to be 1
    }
}

class MyStructure
{
   //For simplicity, I won't put storage related code here

    public int Compare (object o1, object o2)
    {
       //let's suppose o1 and o2 are always of same type
       switch (o1.GetType())
       {
            case TypeCode.Single: return Compare<Single> ((Single)o1 , (Single)o2);  
            case TypeCode.Double: return Compare<Double> ((Double)o1 , (Double)o2); 
            case TypeCode.String: return Compare<String> ((String)o1 , (String)o2); 
            //and so on.....
       }
       return 0;            
    }

    //NOTE: code below won't work
    //But my logic is: use a Dictionary to store a map from "Type" to "Comparison<T>"
    //When doing the comparison, we first examine if there exists one Comparison<T> for 
    //Type T in the Dictionary

    //Compile failed here
    public Dictionary <Type , Comparison<T> > CustomizedComparers = new Dictionary <Type , Comparison<T> > ();

    private int Compare<T> (T a , T b)
    {
         if (CustomizedComparers.ContainsKey(typeof(T)))
         {
            Comparison<T> comp = CustomizedComparers[typeof(T)];
            return comp (a , b);
         }
         else return Comparer<T>.Default.Compare(a, b);
    }
}

Any comments, suggestions and insights are welcomed! Thank you guys.

  • 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-08T22:30:46+00:00Added an answer on June 8, 2026 at 10:30 pm

    You can create Dictionary<Type, Delegate> and cast delegates to correct type when they are requested. Consider following helper class instead of plain Dictionary<Type, Delegate>:

    public class ComparersCollection
    {
        private readonly Dictionary<Type, Delegate> _comparers =
            new Dictionary<Type,Delegate>();
    
        public void OverrideComparison<T>(Comparison<T> comparison)
        {
            if(comparison == null)
            {
                _comparers.Remove(typeof(T));
            }
            else
            {
                _comparers[typeof(T)] = comparison;
            }
        }
    
        public Comparison<T> GetComparison<T>()
        {
            Delegate comparison;
            if(_comparers.TryGetValue(typeof(T), out comparison))
            {
                return (Comparison<T>)comparison;
            }
            else
            {
                return Comparer<T>.Default.Compare;
            }
        }
    }
    

    Now you can use:

    Comparison <string> myStringComparer = (x, y) => -x.CompareTo(y);
    s.CustomizedComparers.OverrideComparison(myStringComparer);
    

    and

    var comparison = CustomizedComparers.GetComparison<T>();
    return comparison(a, b);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have question about normalization. Suppose I have an applications dealing with songs. First
I have a question about Java Generics. If I define a class like this:
I have a question about using generics with collections. ArrayList<Integer> al=new ArrayList<Integer>(); We know
I have a question about .net generics. Consider the following code: public abstract class
I have a question about Java Generics and Collections. It's considered good practice to
I have a Assignment question about Java Generics. The given class is Product.java. It
I'm just learning about generics and have a question regarding method return values. Say,
I have a simple question about .net delegates. Say I have something like this:
I have a generic question about javascript specification or implementation of functions pointer (delegates?)
I have a Java question about generics. I declared a generic list: List<? extends

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.