Why ref and out are not sufficient to disambiguate overloaded in C#?

前端 未结 5 1641
终归单人心
终归单人心 2021-01-18 21:41

For example, why this method Max(ref int x, ref int y) is not considered overload of Max(int x, int y)? Why is the same with out?

5条回答
  •  不知归路
    2021-01-18 21:59

    Let's write some code:

    static void M1(int y)
    {
        Console.WriteLine("val");
    }
    
    static void M1(ref int y)
    {
        Console.WriteLine("ref");
    }
    
    //static void M1(out int y)  // compile error
    //{
    //    Console.WriteLine("out");
    //}
    
    static void Main2()
    {
        int a = 3;
    
        M1(a);
        M1(ref a);
    //    M1(out a);
    
    }
    

    Ther only is a conflict between the ref and out versions. Comment out the out parameter method and it compiles and runs as expected: Output is val and ref .

提交回复
热议问题