Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

c# 4.0 - Why is it not possible to declare a function with VAR return type?

In C#, we have var data type but we can't use it as functions return type.
Why this is not possible?

public var myFunction()
{
    var = some operations
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe it's partly due to the design of the compiler. Eric Lippert blogged about why fields can't use implicit typing, and I suspect some of the same arguments hold for methods.

But you could easily end up with ambiguity anyway. For example:

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

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

What should the type be here?

A simpler example:

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

Admittedly this sort of ambiguity could simply be disallowed, but I suspect that the design team felt that the added complexity of both design and implementation wasn't worth the benefit. Don't forget that they're running with limited resources - given a choice between var for methods and async/await, I'd pick the latter in a heartbeat. (Admittedly there are other features I'd have picked instead of dynamic, but that's a different matter...)

Note that return type inference is performed for lambda expressions, so the very idea of it isn't crazy. For example:

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

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

There the compiler infers the complete type of the lambda expression when it performs overload resolution on Select, converting it to a Func<string, int>. It's not inconceivable to apply the same ideas to methods - just complicated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...