views:

801

answers:

7

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.

+4  A: 

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.

Jon Skeet
The example show in small way what I try to do. 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.
Daok
Consider using a map from the type to a delegate to call. See http://stackoverflow.com/questions/298976/c-is-there-a-better-alternative-than-this-to-switch-on-type
Jon Skeet
this is more what I search I think, how do you setup the map? Dictionnary with <Type,Delegate> ?
Daok
Dictionary<Type,Action> so you can just call the action.
Jon Skeet
Action doesn't return value and my method need to return value. What about you create a new post with the solution. Here is my try: Dictionary<Type, delMapper> map = new Dictionary<Type, delMapper>(); public Parser() {map.Add(typeof(ObjectType1), new delMapper(action)); }
Daok
But it doesn't work, I am still trying to do it...
Daok
HEre is what you are talking about : http://dotnetperls.com/Content/Action-Dictionary.aspx but it doesn't have parameter or return value. But thx for the info, I'll follow to work on it.
Daok
If you need to return a value, then make it Func instead. I was going by your sample code.
Jon Skeet
Doesn't exist in C# 2.0.
Daok
So add it - it's just a delegate. See http://csharpindepth.com/Articles/Chapter1/Versions.aspx for some code you can cut and paste. (Note that it's .NET 2.0 it doesn't exist in - C# itself doesn't specify any delegate types.)
Jon Skeet
It doesn't work for the reason that when you create the Dictionnary you need to specify the type, Since I have a lot of object I can't do it : Dictionary<Type, Func<???>> map = new Dictionary<Type, Func<???>>();
Daok
Ah, you hadn't said that it needed to return an instance of T. In that case you'll have to just make it a Func<object> and cast it in Execute.
Jon Skeet
ok thx for all, If I have do do that i'll keep my big IF/Else IF.
Daok
+2  A: 
Rob Prouse
Unnecessary, "obj" is already of type T, you don't need to cast it.
Lasse V. Karlsen
The first ONE does NOT work. The second one work!
Daok
The second work if the "as" follow a real type and not the T (oops I haven't read well the solution I think). So it works but I still require to do a lot of IF...
Daok
+4  A: 

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.

workmad3
Yes but I can't do 100 class for that... I have to tell you that we have a lot of method here because it's the database object builder. Yes I have considered but I would like to keep all the database object building in the same class
Daok
And I wouldn't change all BusinessLogic to have IAction ... this option is really not good for the situation.
Daok
Fair enough... it sounds like a job for an interface though. If the only reason you aren't considering interfaces is the fact you have a lot of methods and classes to modify, then you could write a script to automate that process for you :)
workmad3
The class require to do its job not the loading of it or other task (this way if we change the loading way or other method the Business object is not affected. I do not believe with this context that an Interface is required BUT thx a lot (The way your code is is great for other purpose)
Daok
A: 

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

BCS
If anyone is googling for information, these are called constraints. You can constrain based on type, inheritance or implementation, etc.http://msdn.microsoft.com/en-us/library/d5x73970.aspx
joshua.ewer
+2  A: 

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.

David B
Nice answer and I will vote you up BUT the problem is the method in reality is from an Interface and I couldn't not change that interface to overload it for all type.
Daok
+1  A: 

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.

David B
The code is this way because sometime we get the data from the cache (unserialize) and we have a new reference this is why we need to return. We need to pass the object by parameter to know which object to load... you get it?
Daok
It doesn't matter to me if the data comes from the cache or from Mongolia, you've got a pass-by-value problem if any of the types are value types.
David B
A: 

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.

Guge