geoyws
geoyws

Reputation: 3697

Is there such a thing as "public var Method()"?

I've done some research and found nothing so far.

public var Method()
{
    //Do something
}

Upvotes: 3

Views: 152

Answers (3)

Mike Zboray
Mike Zboray

Reputation: 40838

No, there isn't. Per the specification, using the identifier var for implicit typing is only allowed in the context of a local variable declaration. Eric Lippert's article on why var is not valid for fields raises a number of issues with implementing it outside the local variable context, which apply to using it in method signatures as well. Two issues are raised:

  1. It significantly complicates analysis of types at the top level since many of the compiler's algorithms for overload resolution were written assuming all top level types are known.
  2. The inferred type of the var field could be an anonymous type and there is no standard for how these types can be unified across assemblies.

As is pointed out in the article, these are not insurmountable problems but they indicate that there could be significant costs to implementing var outside a local variable declaration. The article was written in 2009, perhaps it is easier to implement in the Roslyn compiler.

Upvotes: 3

Avi Turner
Avi Turner

Reputation: 10456

From the documentation:

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed 
int i = 10; //explicitly typed

If you have a function with a public var Method() signature, The return type is not expressed implicitly, and therefore the compiler cannot determine the type on it's on.

So, the answer to you question is: No, such a signature will not compile....

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65087

You can use dynamic.

public dynamic Method() {
}

..however, you should probably re-think your design. Your consumers of this method will not know what type you pass out. Therefore, you may as well split it into individual methods with expected types. The amount of logic you'll write just to make sure what you have returned out is what you expect means splitting the functions with proper types is less work.

Also, dynamic is not the same as var. dynamic means "anything".. var means "whatever is declared on the other side of this assignment". Since you can't use var in the context of a method return value (it isn't an assignment).. the only option is dynamic. When you can return "anything" out of a method, your code is very open to bugs.

TLDR: You're setting yourself up for a headache. Don't do it.

Upvotes: 14

Related Questions