What is the reason for which a function's return type cannot be var?
e.g.
public var SomeMethod()
{
return "hello";
}
error:
The contextual keyword var
may only appear wit开发者_JAVA百科hin a local variable declaration
Thanks
C# only supports type inference for local variables. It doesn't support it for the return type of a non-anonymous function. This is a design decision. It's possible that they change it in the future. Languages like F# do in fact support return type inference so there's no inherent impossibility involved here. Of course, sometimes, the inferred return type may be ambiguous and requires further clarification in the languages that support it:
// not real C#:
public var Method(bool returnInt) {
if (returnInt) return 42; else return true;
}
// what's the return type of Method is going to be? ValueType? object? ...?
I would recommend that you read Why no var on fields?:
In my recent request for things that make you go hmmm, a reader notes that you cannot use "var" on fields.
Now you don't want to use var
for a field but you do want to use it for another purpose other than how it is specified. That article should give you a little insight into the compiler implementation around the var
feature (and why, perhaps, var
is not a valid return type).
Now, all that being said, it would be perfectly valid for the return type of a method to be inferred by the type of the return expression.
Consider a potentially ambiguous situation, a slight enhancement of your question:
public var SomeMethod() {
return DateTime.Now.Second % 2 == 0 ? "hello" : 3;
}
Should the compiler raise an error or infer type System.Object
?
Only at runtime can the correct type be resolved between int
and string
.
var
must be used on the left side of an initialization statement because its type is inferred by the C# compiler from the resulting data type on the right side.
var thing = 3;
// infers System.Int32 from right side.
var thing = 3L;
// infers System.Int64 from right side.
// This also applies to methods and things that have a defined type on the right side:
var thing = obj.AnyMethod();
If you could use var in place of the method return type, how could the C# compiler easily infer that type from all the logic inside the method?
var MyCall() { // ??? could be various things really
// lots of logic...
}
Available C# alternative
However, what you might be looking for in the C# language is to allow an interchangeable return type from your method via a Type Parameter and Generics like so:
T MyCall<T>() {
// lots of logic...
The caller can then specify the type that will be returned. Example:
An int.
var result = MyCall<int>();
// var will infer System.Int32
A string.
var result = MyCall<string>();
// var will infer System.String
精彩评论