Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Automatically pick most related method for arguments

I have the following code in C#:

static void Main(string[] args)
{
    Object rect = new Rectangle();
    Object circle = new Circle();
    Console.WriteLine(count(rect, circle));
}

public static int count(Object obj1, Object obj2)
{
    return 4;
}

public static int count(Rectangle rect, Circle circ)
{
   return 0;
}

The program outputs 4, however, I'd like it to pick the method that is more specific to this case, which would be the second method. I can't simply define the variables rect and circle as their specific types, because in the context of my code, I don't know what their types are.

Is there something entirely wrong about the way I am trying to implement this, or is there a fairly simple way to automatically choose the correct method?

like image 579
Dan Doe Avatar asked Dec 29 '25 13:12

Dan Doe


2 Answers

If you really want to select the method at runtime, you can use dynamic. Note that it is slow.

dynamic rect = new Rectangle();
dynamic circle = new Circle();
Console.WriteLine(count(rect, circle));

And I do still feel that the pattern you should use is different, but unless you tell us what you really want, it is difficult to explain what should be the real pattern.

For example without using dynamic you could:

public static int count(Object obj1, Object obj2)
{
    if (obj1 is Rectangle && obj2 is Circle)
    {
        return count((Rectangle)obj1, (Circle)obj2);
    }

    return 4;
}

Note that I still do feel that there is something wrong here, because what happens if you

Console.WriteLine(count(circle, rect));

(I inverted circle and rect). Do you want the same result or different? In both cases, you'll have to handle that case too!

Other problem: there is an exponential growth of the number of cases you have to handle. With 2 figures, you have 4 cases (rect + rect, circle + circle, rect + circle, circle + rect), but with 4 figures you already have 16 cases, with 6 figures 36 cases...

like image 138
xanatos Avatar answered Jan 01 '26 03:01

xanatos


You need to trigger dynamic dispatch (runtime evaluation) in your code by using the dynamic keyword:

static void Main(string[] args)
{
    Object rect = new Rectangle();
    Object circle = new Circle();
    Console.WriteLine(count((dynamic) rect, (dynamic) circle));
}

In your example, this will print 0 instead of 4.

like image 43
jbartuszek Avatar answered Jan 01 '26 01:01

jbartuszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!