Why is it impossible to declare a function with a return type of VAR?

In C #, we have a data type var, but we cannot use it as the return type of a function.
Why is this impossible?

public var myFunction()
{
    var = some operations
}
+5
source share
3 answers

I believe this is partly due to the compiler design. Eric Lippert blogged on why fields cannot use implicit typing, and I suspect some of the same arguments are stored for methods.

But in any case, you can easily get ambiguity. For instance:

var Method1(bool callMethod2)
{
    return callMethod2 ? Method2() : null;
}

var Method2()
{
    return Method1(false);
}

What should be the type?

The simplest example:

var Method1(bool throwException)
{
    if (!throwException)
    {
        return Method1(true);
    }
    throw new Exception("Bang!");
}

, , , , , . , - var async/await, . ( , , dynamic, ...)

, -, . :

IEnumerable<string> x = new[] { "x", "y", "z" };

var result = x.Select(s => { return s.Length; }); // Long form

, Select, Func<string, int>. - ​​ .

+12

var #. . , . # 4.0 dynamic:

public dynamic myFunction()
{
    var = some operations
}
+2

I think this can ruin the method overload rules.

-2
source

All Articles