mo.
mo.

Reputation: 3544

Are Generics A Good Way To Resolve Overloaded Methods?

two minutes ago, i came up with an idea to select overloaded methods with an interface. we currently using UIP from Microsoft application blocks. they use an OnEnterTask-Method with one object parameter in each controller. but this leads to an type-checking mess.

so i came up with the idea to use an interface to select the correct method:

interface IAcceptTaskArguments<TInputArguments> where TInputArguments : InputArguments
{
   void OnEnterTask(TInputArguments arguments);
}

is it a good practice to do something like this to avoid that typechecking-mess?

thank you guys.

Upvotes: 1

Views: 167

Answers (1)

ArBR
ArBR

Reputation: 4082

I prefer to use generics versus method overloading. When overloading is required I prefer to pass an instance of a class (or an interface) having all the parameters, then checking for default customized values for each parameter, if the value is the default it means no value was given for such parameter.

With version 4.0 of Microsoft's Framework, it is easier to use generics because, there is some keyword named dynamic by which you can call a static method from generic methods:

namespace Layer.Logic
{
    public class EntityObjectCommands : LogicContextBase, IEntityObjectCommands
    {
        public Tresult Get<Tcommand, Tresult>(Tcommand command) where Tcommand : ICommandGet
        {
            Tresult result = default(Tresult);
            DBEntityObjectCommands dbfactory = new DBEntityObjectCommands(GetDataServiceParam(dbserver));
            result = dbfactory.Get<Tcommand, Tresult>(command);     
            return result;
        }
    }
}
namespace Layer.Data
{
    public class DBEntityObjectCommands : IEntityObjectCommands
    {
        public Tresult Get<Tcommand, Tresult>(Tcommand command) where Tcommand : ICommandGet
        {
          Tresult result = default(Tresult);
          OleDbCommandInfo commandInfo = DBCommandProvider<Tcommand>.Get(command);

          //-- implement logic to use [commandInfo] ...........

          return result;
        }       
    }   
    public static class DBCommandProvider<Tcommand> where Tcommand : ICommand
    {
        public static OleDbCommandInfo Get(Tcommand command)
        {   
            return DBCommands.Get( (dynamic)command );
        }
    }   
}

Upvotes: 1

Related Questions