Overloading generic methods

22,302

Solution 1

You could do :

public bool Save<T>(T entity) where T : class
{ ... some storage logic ... }

public bool Save(SpecificClass entity)
{ ... special logic ... }

For example:

public class SpecificClass
{
}

public class Specializer
{
    public bool GenericCalled;
    public bool SpecializedCalled;

    public bool Save<T>(T entity) where T : class
    {
        GenericCalled = true;
        return true;
    }

    public bool Save(SpecificClass entity)
    {
        SpecializedCalled = true;
        return true;
    }
}

public class Tests
{
    [Test]
    public void TestSpecialization()
    {
        var x = new Specializer();
        x.Save(new SpecificClass());
        Assert.IsTrue(x.SpecializedCalled);
        Assert.IsFalse(x.GenericCalled);
    }
}

Solution 2

Well basicly C# does not allow template specialization, except through inheritence like this:

interface IFoo<T> { }
class Bar { }

class FooBar : IFoo<Bar> { }

At least it does not support this during compile time. However you can use RTTI to do what you are trying to achieve:

public bool Save<T>(T entity)
{
    // Check if "entity" is of type "SpecificClass"
    if (entity is SpecificClass)
    {
        // Entity can be safely casted to "SpecificClass"
        return SaveSpecificClass((SpecificClass)entity);
    }

    // ... other cases ...
}

The is expression is pretty handy to do runtime type checks. It works similar to the following code:

if (entity.GetType() == typeof(SpecificClass))
    // ...

EDIT : It is pretty common for unknown types to use the following pattern:

if (entity is Foo)
    return DoSomethingWithFoo((Foo)entity);
else if (entity is Bar)
    return DoSomethingWithBar((Bar)entity);
else
    throw new NotSupportedException(
        String.Format("\"{0}\" is not a supported type for this method.", entity.GetType()));

EDIT 2 : As the other answers suggest overloading the method with the SpecializedClass you need to take care if you are working with polymorphism. If you are using interfaces for your repository (which is actually a good way to design the repository pattern) there are cases where overloading would lead to cases in which you are the wrong method get's called, no matter if you are passing an object of SpecializedClass to the interface:

interface IRepository
{
    bool Save<T>(T entity)
        where T : class;
}

class FooRepository : IRepository
{
    bool Save<T>(T entity)
    {
    }

    bool Save(Foo entity)
    {
    }
}

This works if you directly call FooRepository.Save with an instance of Foo:

var repository = new FooRepository();
repository.Save(new Foo());

But this does not work if you are calling the interface (e.g. if you are using patterns to implement repository creation):

IRepository repository = GetRepository<FooRepository>();
repository.Save(new Foo());  // Attention! Call's FooRepository.Save<Foo>(Foo entity) instead of FooRepository.Save(Foo entity)!

Using RTTI there's only one Save method and you'll be fine.

Solution 3

Because function and operator overloads involving generics are bound at compile-time rather than run-time, if code has two methods:

public bool Save<T>(T entity) ...
public bool Save(SomeClass entity) ...

then code which tries to call Save(Foo) where Foo is a variable of some generic type will always call the former overload, even when the generic type happens to be SomeClass. My suggestion to resolve that would be to define a generic interface ISaver<in T> with a non-generic method DoSave(T param). Have the class that provides the Save method implement all of the appropriate generic interfaces for the types it can handle. Then have the object's Save<T> method try to cast this to an ISaver<T>. If the cast succeeds, use the resulting ISaver<T>; otherwise perform a generic save. Provided that the class type declaration lists all of the appropriate interfaces for the types it can save, this approach will dispatch Save calls to the proper methods.

Share:
22,302

Related videos on Youtube

Patrick Dench
Author by

Patrick Dench

By day: ReactJS Developer By night: Hobby developer

Updated on July 19, 2020

Comments

  • Patrick Dench
    Patrick Dench almost 4 years

    When calling a generic method for storing an object there are occasionally needs to handle a specific type differently. I know that you can't overload based on constraints, but any other alternative seems to present its own problems.

    public bool Save<T>(T entity) where T : class
    { ... some storage logic ... }
    

    What I would LIKE to do is something like the following:

    public bool Save<SpecificClass>(T entity)
    { ... special logic ... }
    

    In the past our team has created 'one-off' methods for saving these classes as follows:

    public bool SaveSpecificClass(SpecificClass sc)
    { ... special logic ... }
    

    However, if you don't KNOW that function exists, and you try to use the generic (Save) then you may run into a host of problems that the 'one-off' was supposed to fix. This can be made worse if a new developer comes along, sees the problem with the generic, and decides he's going to fix it with his own one-off function.

    So...

    What are the options for working around this seemingly common issue?

    I've looked at, and used UnitOfWork and right now that seems to be the only option that actually resolves the problem - but seems like attacking a fly with a sledgehammer.

    • Panagiotis Kanavos
      Panagiotis Kanavos about 11 years
      Unlike C++, C# doesn't allow template specialization
  • Carsten
    Carsten about 11 years
    Nothing is wrong with it, but it's still an overload, not a specialization. ;)
  • Peter Ritchie
    Peter Ritchie about 11 years
    Question is about "overloading"... :)
  • Carsten
    Carsten about 11 years
    Nobody has told something different... I was just answering the OP's comment "However, if you don't KNOW that function exists, and you try to use the generic (Save) then you may run into a host of problems that the 'one-off' was supposed to fix. This can be made worse if a new developer comes along, sees the problem with the generic, and decides he's going to fix it with his own one-off function.". And it works, too. It's just an alternative to the already provided answers. No need to downvote it...
  • Carsten
    Carsten about 11 years
    Also I prefer using RTTI, because it makes it easier for the developer to do it right (There is only one method to call), instead of doing it wrong (perhaps calling the wrong method). Also take a look at the question comments, because specialization is what the OP does (no matter if he asks for "overloading").
  • Peter Ritchie
    Peter Ritchie about 11 years
    It's not "template specialization" sure, but an overload with a specific argument that overloads a generic method seems like specialized behaviour to me.
  • Carsten
    Carsten about 11 years
    In fact my answer does not provide "template specialization", either, but the behaviour is also the same! So why downvoting it?
  • Carsten
    Carsten about 11 years
    btw... there is a difference in "template specialization" and "overloading" like you described it: imagine the interface IFoo defines a method Save<T>. The specialization CFoo implements IFoo and provides an overload Save(Specialized s) like you described it. A client calls the interface IFoo foo = GetFoo(); foo.Save(new Specialized()); which behaviour acts more like what the OP wants? RTTI or overloading?! Right... RTTI works, while overloading would still call Save<T>. ;-)
  • jam40jeff
    jam40jeff about 11 years
    +1 Overloads may not always work, as @Aschratt pointed out. Another case they wouldn't work is if the Save method was called from another generic type with the same constraint. This is the likely the best way to consistently get the desired behavior in C#.
  • MarkusParker
    MarkusParker almost 7 years
    I could not get it to work: The generic version of the function was called in any case.
  • Peter Ritchie
    Peter Ritchie almost 7 years
    @MarkusParker Can you provide an example as this should work fine, as detailed by my update that shows it working in a unit test. Keep in mind that the variable used to pass the SpecificClass must be of type SpecificClass unless it's a dynamic class as C# does compile-time polymorphism.
  • MarkusParker
    MarkusParker almost 7 years
    class Test { public bool GenericCalled; public bool SpecializedCalled; public bool Save<T>(T entity) { GenericCalled = true; return true; } public bool Save(int entity) { SpecializedCalled = true; return true; } public void HandleGenericType<T>() { Save(default(T)); } } Here HandleGenericType<int>() calls the generic version.
  • Peter Ritchie
    Peter Ritchie almost 7 years
    @markusParker Ah, okay. That's the compile-time polymorphism kicking in. At compile time, HandleGenericType doesn't know that an int could be called and specifically call Save(int) so it links to the generic Save<T>. You can get it to do the run-time polymorphism by casting default<T> to dynamic. e.g.: Save((dynamic)default(T));`
  • Iamsodarncool
    Iamsodarncool about 6 years
    @PeterRitchie - thank you so much!! I've been googling for 20 minutes trying to find the answer, and this was it!
  • sschoof
    sschoof almost 5 years
    A little gotcha is, that a class derived from SpecificClass will go call the generic Save and not the Specific Save method.
  • Peter Ritchie
    Peter Ritchie almost 5 years
    @sschoof yep, use the new keyword to access the new Save through a variable of type of the new class.
  • sschoof
    sschoof almost 5 years
    @PeterRitchie I do not understand how the new keyword helps. Having something likeclass DerivedClass : SpecificClass and run x.Save(new DerivedClass()) calls the Generic Save method and not the Specialized. How can I fix this with an new?
  • Peter Ritchie
    Peter Ritchie almost 5 years
    @sschoof Not sure what you're trying to accomplish to know what a "fix" is. If you're trying to get runtime dispatch, (i.e. calling a type's method based on what the argument is at run-time, not compile-time) then this won't do that for you. But, C# doesn't do that sort of thing just through the type system.