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

Edit: This was accidentally posted twice. Original: VB.NET Importing Classes I've seen some code
EDIT: I missed a crucial point: .NET 2.0 Consider the case where I have
What are extension methods in .NET? EDIT: I have posted a follow up question
Is there a .net equivalent to the C++ unexpected()/set_unexpected() functionality? Edit: Sorry--I omitted some
Say you have something like an ASP.NET ASP:DetailsView to show and edit a single
Is there a .NET API for OpenOffice? EDIT: Is there a OpenOffice SDK for
I'm looking for a way to edit a configuration file (web.config in an asp.net
Is there any disadvantage you face it when you using asp.net MVC? EDIT If
Edit: From another question I provided an answer that has links to a lot
I am a VB.net winforms programmer attempting to build an ASP.Net app. I use

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.