Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Method overloading using dynamic params

I'm trying to write a tool for serialization of values. And I was hoping to get some nice syntax working.....

            float f = 9999.0f;
            ByteSerializer s = new ByteSerializer ();
            s.Write(f);

Where the params of Write() could be anything and any number:

    public void Write (params dynamic[] objects)
    {

        for (int i =0;i<objects.Length;i++) {

            byteList.AddRange (GetBytes (objects[i]));

        }
    }

GetBytes() should now be called according to the type of the object that was passed:

    public  byte[] GetBytes ( object v)
    {
    //Shouldn't actually do anything since it's a dummy
        return new byte[0];
    }


    public  byte[] GetBytes ( System.Single v)
    {
    //Why is this not called?

        return BitConverter.GetBytes (v);

    }

But it will always go straight for the method that takes an object as parameter. I initially tried (params object[]) as method parameters and found this behaviour to be rather obvious. But why does dynamic[] behave the same?

objects[i].GetType() reports a System.Single so what's going on here? Is what I am trying to do just not possible?

like image 535
Arbelzapf Avatar asked Jul 06 '26 20:07

Arbelzapf


1 Answers

There is no reason this shouldn't work with dynamic exactly as you described. One of the primary features of the DLR is to do at runtime what would have been done at compile time if the types had been known then. For example, the following program:

public class Program
{
    public static void Main(string[] args)
    {
        WriteItems("a string", (byte)1, 3f, new object());
    }

    private static void WriteItems(params dynamic[] items)
    {
        foreach(dynamic item in items)
        {
            Write(item);
        }
    }

    private static void Write(byte b)
    {
        Console.WriteLine("Write byte: {0}", b);
    }

    private static void Write(float f)
    {
        Console.WriteLine("Write Single: {0}", f);
    }

    private static void Write(string s)
    {
        Console.WriteLine("Write string: {0}", s);
    }        

    private static void Write(object o)
    {
        Console.WriteLine("Write object: {0}", o);
    }
}

Produces the output:

Write string: a string
Write byte: 1
Write Single: 3
Write object: System.Object

like image 125
Mike Zboray Avatar answered Jul 09 '26 09:07

Mike Zboray



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!