Is there a difference between return myVar vs. return (myVar)?

前端 未结 4 1324
清酒与你
清酒与你 2020-12-07 14:19

I was looking at some example C# code, and noticed that one example wrapped the return in ()\'s.

I\'ve always just done:

return myRV;
4条回答
  •  失恋的感觉
    2020-12-07 15:15

    There are corner cases when presence of parentheses can have effect on the program behavior:

    1.

    using System;
    
    class A
    {
        static void Foo(string x, Action y) { Console.WriteLine(1); }
        static void Foo(object x, Func, int> y) { Console.WriteLine(2); }
    
        static void Main()
        {
            Foo(null, x => x()); // Prints 1
            Foo(null, x => (x())); // Prints 2
        }
    }
    

    2.

    using System;
    
    class A
    {
        public A Select(Func f)
        {
            Console.WriteLine(1);
            return new A();
        }
    
        public A Where(Func f)
        {
            return new A();
        }
    
        static void Main()
        {
            object x;
            x = from y in new A() where true select (y); // Prints 1
            x = from y in new A() where true select y; // Prints nothing
        }
    }
    

    3.

    using System;
    
    class Program
    {
        static void Main()
        {
            Bar(x => (x).Foo(), ""); // Prints 1
            Bar(x => ((x).Foo)(), ""); // Prints 2
        }
    
        static void Bar(Action> x, string y) { Console.WriteLine(1); }
        static void Bar(Action> x, object y) { Console.WriteLine(2); }
    }
    
    static class B
    {
        public static void Foo(this object x) { }
    }
    
    class C
    {
        public T Foo;
    }
    

    Hope you will never see this in practice.

提交回复
热议问题