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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:10:11+00:00 2026-05-13T09:10:11+00:00

Edit: C# 3.0, net 3.5. I am C++ programmer, so maybe I miss some

  • 0

Edit: C# 3.0, net 3.5.

I am C++ programmer, so maybe I miss some simple solution in C#.

Simplified example:
I have several classes inherited from class MyBase (with method Inc). The inherited classes may override Inc. I have several overloaded “functions” (static methods) for the inherited classes:

void Print(MyInherited1 i1) ....
void Print(MyInherited2 i2) ....

and so on. Edit: those methods are “external” to the MyBase and MyInherited, they are not part of any of those classes.

I have generics function that modify its argument and call the Print function:

void Transform<T>(T t)
{
    t.Inc();
    Print(t);
}

Edit: this is simplified example, in real code I cannot convert the Transform method to non-generic one using just polymorphism.

Now, in C++ it would work just like that. However in C# method Inc is unknown. So I specify that T is of type MyBase.

void Transform<T>(T t) where T : MyBase
{
    t.Inc();
    Print(t);
}

but I still have the problem with Print — there is no such method for the base class.

As a workaround I used ugly (!) solution — PrintProxy where I put several

if (t is Inherited1)
  Print(t as Inherited1);
else if ...

How to mix those two concepts — overloading and generics? Nice, C# way?

Thank you in advance for help.

  • 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-13T09:10:12+00:00Added an answer on May 13, 2026 at 9:10 am

    One option in C# 4 is to use dynamic typing:

    void Transform<T>(T t)
    {
        t.Inc();
        dynamic d = t;
        Print(d);
    }
    

    That will perform the overload resolution for you at execution time – which is basically the best you can do unless you can provide a genuinely generic Print method, as there will only be one version of Transform generated.

    Note that there’s no real need to be generic at this point – you could replace it with:

    void Transform(MyBase t)
    {
        ...
    }
    

    I typically find that constraints based on interfaces are more useful than those based on classes, unless I’m also doing something else generic (such as creating a List<T> which should be of the right actual type).

    Obviously this dynamic approach has downsides:

    • It requires .NET 4.0
    • It’s slower than a compile-time binding (although it’s unlikely to be significant unless you’re calling it a heck of a lot)
    • There’s no compile-time validation (you can add an overload which takes object as a sort of fallback to provide custom error handling, but you still have to wait until execution time)

    Basically this is just a difference between .NET generics and C++ templating – they’re very different creatures, even if they tackle many similar problems.

    Rather than having static Print methods, is there any reason you can’t write an abstract Print method in MyBase, and override it in each class? That feels like a more OO solution anyway, to be honest – although obviously it doesn’t make sense if the printing is actually somewhat logically distant from the class itself. Even if you don’t want the actual Print method in the original type hierarchy, might you be able to expose enough functionality to let you write a virtual Print method? I assume all these methods should come up with some similar kind of result, after all.

    EDIT: A couple of alternative ideas…

    Passing in the printer

    You can pass in a delegate to do the printing. If you’re calling this from a non-generic context which knows the actual type, you can take advantage of method group conversions to make this simple. Here’s a short but complete example:

    using System;
    
    class Test
    {
        static void SampleMethod<T>(T item, Action<T> printer)
        {
            // You'd do all your normal stuff here
            printer(item);
        }
    
        static void Print(string x)
        {
            Console.WriteLine("Here's a string: {0}", x);
        }
    
        static void Print(int x)
        {
            Console.WriteLine("Here's an integer: {0}", x);
        }
    
        static void Main()
        {
            SampleMethod(5, Print);
            SampleMethod("hello", Print);
        }
    }
    

    Use a type/delegate dictionary

    Another option is to have a Dictionary<Type, Delegate> containing the printing methods. This could either be inlined (if the printing methods are simple) or something like this:

    static readonly Dictionary<Type, Delegate> Printers = 
        new Dictionary<Type, Delegate>
    {
        { typeof(MyClass1), (Action<MyClass1>) Print },
        { typeof(MyClass2), (Action<MyClass2>) Print },
        { typeof(MyClass3), (Action<MyClass3>) Print },
    };
    

    Then in your method:

    Delegate printer;
    if (Printers.TryGetValue(typeof(T), out printer))
    {
        ((Action<T>) printer)(t);
    }
    else
    {
        // Error handling
    }
    

    This is another execution time solution though, and you’d need a bit more work if you wanted it to handle further derivation (e.g. walking up through the base classes if it can’t find the relevant printer).

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

Sidebar

Related Questions

I took over an ASP.NET application and have found this throughout several classes in
I'm wondering if there is a good example of how to edit ASP.NET Profile
EDIT: I am using VS2008, .NET 3.5 I have a DataTable, which is populated
I have been using the .NET WebBrowser control in edit mode as part of
In my ASP.NET MVC app, I have a fairly complex edit page which combines
Edit 1 I am confused with the statement below, taken from What ASP.NET Programmers
I have what should be a simple thing but my unfamiliarity with .NET and
Is there a tool where you can edit a .NET dll directly? .net reflector
EDIT: This post was originally specific to ASP.NET, but after thinking about it I'm
I am using C#.net I want to add custom edit/delete buttons to my GridView1

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.