-1

I would like to create generic method for specified classes. Pseudo-code could be like below:

void doSend(Guid g)
{
   //code    
}
void doSend(Int32 i)
{
   //code     
}
void Send<T>(T param) where T:Guid or Int32
{
    //lots of code
    doSend(param) 
    //lots of code
}

I do not want to copy and paste whole implementation to change only one line.

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116

3 Answers3

2

Is there not a reason you can do this?

void Send(Guid param)
{
    ChunkA();
    doSend(param);
    ChunkB();
}

void Send(Int32 param)
{
    ChunkA();
    doSend(param);
    ChunkB();
}

void ChunkA()
{
  //lots of code
}

void ChunkB()
{
  //lots of code
}

Also, if you're expecting only those two types... using generics would be a slight abuse of it. You might want to step back and rethink your design.

Edit: Since you mentioned in the comments that the code in common is logging and error-handling, I think it makes even more sense to make an overload of Send for Guid and Int32. You could have a Send method that looks more like this:

void Send(Guid param)
{
    try
    {
        LogSend(param);
        doSend(param);
    }
    catch (SendException e)
    {
        HandleSendException(e, param);
    }
}
Jeff B
  • 8,572
  • 17
  • 61
  • 140
0

I do not want to copy and paste whole implementation to change only one line.

Then don't. Move all of the common code into one or more methods, call those methods from the entry points, and leave only the implementation specific to Guid or int in the calling method:

void doSend(Guid g)
{
   //do stuff specific to `Guid`

   doSendCommon(g);   
}
void doSend(Int32 i)
{
   //do stuff specific to `int`

   doSendCommon(i);    
}

private void doSendCommon<T>(T value)
{
   // do stuff common to both
}

Note that doSendCommon can be fully generic but since it's private you control what types can be passed in.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

How about having an interface:

public interface IDoIt
{
    void DoIt();
}

public class Foo : IDoIt
{
    public void DoSomething()
    {

    }

    public void DoIt()
    {
        this.DoSomething();
    }
}

public class Bar : IDoIt
{
    public void DoSomethingElse()
    {

    }

    public void DoIt()
    {
        this.DoSomethingElse();
    }
}

public class GenericClass<T> where T: IDoIt, new ()
{
    public GenericClass()
    {
        T obj = new T();
        obj.DoIt();
    }
}
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55