Home > Mobile >  Difference between params modifier and out and ref modifiers with regards to delegates
Difference between params modifier and out and ref modifiers with regards to delegates

Time:09-19

//Main method
test6 _300er = new(yetan.aa);
        _300er.Invoke(45, 78);

        test7 _200lr = new(yetan.bb);
        _200lr.Invoke(new int[4]);

        test8 max8 = new(yetan.dd);
        double rty = 45;
        max8.Invoke(ref rty);
        test9 max9 = new(yetan.cc);
        max9.Invoke(78);

        test10 neo1 = new(yetan.ee);
        neo1.Invoke(out char ytss);
        test11 neo2 = new(yetan.ff);
        neo2.Invoke('^');


delegate void test6(params int[] h);
delegate void test7(int[] h);
delegate void test8(ref double j);
delegate void test9(double j);
delegate void test10(out char j);
delegate void test11(char j);

class yetan {

    public static void aa(int[] y) {
        Console.WriteLine("params dude");
    }

    public static void bb(params int[] y) {
        Console.WriteLine("params dude");
    }
    public static void cc(double y) {
        Console.WriteLine("jhjgbrvf");
    }
    public static void dd(ref double y) {
        Console.WriteLine("jhjgbrvf");
    }
    public static void ee(out char y) {
        y = '%';
        Console.WriteLine("vvvvvvv");
    }
    public static void ff(char y) {
        Console.WriteLine("vvvvvv");
    }

}

I declared a delagate with params,out,ref modifiers and without
And created methods that will correspond to the signatures of the delagates
I have noticed that if I can poinnt delagte test6 which has params modifier to the method aa that does NOT have a parmas modifier yet It will still work and at the end the params will the method aa will act as if it had the paranms modifier.
and the vice versa is possible too but at the end it ius the delegate that decides whether the method that it is pointing to has the params modifier or not
But for some reason the same is not true with modifiers out and ref
if my delegate test8 did not specify ref its instance would not be able to point to the method dd

Can you please tell me what is the reasoning behind this?

CodePudding user response:

Because a params array is still a regular array, but with syntactic sugar for the call-sites. out and ref however change the behavior of the method (values need to be copied out of the method).

In other words: you can invoke a params method with a real array, but you cannot invoke an out or ref method with a value literal (only with a variable)

  • Related