Question

How can I select the good method (I have in the example below show 2 differents way that doesn't work). I was using instead of a variable of type Object with a IF and IS to do the job but I am trying to avoid using Object and boxing/unboxing. So I thought that Generic could do the job but I am stuck here.

Here is a small snippet of code that illustrate my question:

class Program
{
    static void Main(string[] args)
    {
        Parser p = new Parser();
        ObjectType1 o1 = new ObjectType1();
        p.execute(o1);
        Console.Read();
    }
}

class Parser
{
    public T execute<T>(T obj)
    {
        /*
        if (obj is ObjectType1)
            this.action((ObjectType1)obj);
        else if (obj is ObjectType2)
            this.action((ObjectType2)obj);
        */
        this.action(obj);
        return obj;
    }

    private void action(ObjectType1 objectType1)
    {
        Console.WriteLine("1");
    }

    private void action(ObjectType2 objectType2)
    {
        Console.WriteLine("2");
    }
}


class ObjectType1
{
}

class ObjectType2
{
}

Update

I do not want interface and class. Sorry. I knew that it's not the goal of the question.

Casting with (ObjectType)obj doesn't work but if you do :

        if (obj is ObjectType1)
            this.action(obj as ObjectType1);
        else if (obj is ObjectType2)
            this.action(obj as ObjectType1);

it works... why?

And... I cannot overload for all type the execute method because this method is from an Interface. This is why all need to be called from this method.

Was it helpful?

Solution

No, you can't do this. Generics don't work like C++ templates - the generic method is compiled just once. The only information that the compiler can use for overload resolution is the information it knows about within the generic method, regardless of what code uses it.

As an example to show this, here's a bit of code which may not work how you expect it to:

using System;

class Test
{    
    static void Main()
    {
        string x = "hello";
        string y = string.Copy(x);

        Console.WriteLine(x==y); // Overload used
        Compare(x, y);
    }

    static void Compare<T>(T x, T y) where T : class
    {
        Console.WriteLine(x == y); // Reference comparison
    }
}

It's hard to say the best way to proceed without knowing more about what you want to do.

OTHER TIPS

Have you considered interfaces?

interface IAction
{
   void action();
}

class ObjectType1 : IAction
{
   void action() {
      Console.WriteLine("1");
   }
}

class ObjectType2 : IAction
{
    void action() {
      Console.WriteLine("2");
    }
}

class Parser
{
   public IAction execute(IAction obj)
   {
      obj.action();
      return obj;
   }
}

Edited by OP:

This solution would require to change all Business Logic Object to have this interface. This is really not a thing to do (in my situation). And, in other situation, I always prefer to have clean BusinessObject that doesn't have Interface not related with Business stuff. In my question, I want a solution that is more related with Generic/Object/Delegate method to achieve it. Thx you. This answer won't be accepted.

The class Parser has a lot of private method that are called by the execute method depending of the object type. It needs to redirect to the good method.

The compiler will do this work for you. Just use overloads.

class Parser
{
    public ObjectType1 action(ObjectType1 objectType1)
    {
        Console.WriteLine("1");
        return objectType1;
    }
    public ObjectType2 action(ObjectType2 objectType2)
    {
        Console.WriteLine("2");
        return objectType2;
    }
}

class ObjectType1 { }
struct ObjectType2 { }

Then, called with:

Parser p = new Parser();
p.action(new ObjectType1());
p.action(new ObjectType2());

There's no boxing/unboxing, and the appropriate method gets called.

I haven't tried it, but can you do this?

public T execute<T>(T obj)
{
    this.action((T)obj);
    return obj;
}

(according to comments, doesn't work)

or

public T execute<T>(T obj)
{
    this.action(obj as T);
    return obj;
}

(according to comments, works)

I know you're concerned about boxing/unboxing, so there could be ValueTypes involved here.

public T execute<T>(T obj)   
{        
    this.action(obj);
    return obj;
}

Supposing that action is modifying obj, and also supposing that modification is important to the caller (which is why you're returning the value back to the caller). This code has a nasty pass-by-value defect.

Consider this code:

    public int execute(int obj)   
    {        
        this.action(obj);
        return obj;
    }

    public void action(int obj)
    {
        obj = obj + 1;
    }

Called in this way.

int x = p.execute(1);

x is 1, not 2.

Generics happens in compile time. It is best used when you want the same code to apply to different types. It is not dynamic, so it won't help you switch between methods depending on input types.

Overloading resolving as in David B's reply works, but also happens during compile time.

The code in your update does the same thing. It casts (after careful checking of types) and then uses overloading to resolve the method.

I feel that you want to switch methods based on runtime input.

You could get a more dynamic behaviour if you used Reflection.

        public object execute(object obj) 
        {
            MethodInfo m = typeof(Parser).GetMethod(
                "action", 
                BindingFlags.Instance | BindingFlags.NonPublic, 
                null, 
                new Type[] { obj.GetType() }, 
                null);
            m.Invoke(this, new object[] { obj });
            return obj; 
        } 

It is perhaps a little fragile, but it works in the example.

IIRC you can use the "where" clause to allow this

public T execute<T>(T obj) where : /* somthing */
{
}

I always have to Google that one my self so I'll leave it at that.

edit: reading some comments. I would not advise calling type specific code. Rather put that code in a virtual function and call that. The call signature might get long, but that's what auto complete is for.

Koodos to joshua.ewer for finding the man page

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top