Eitan H.S.
Eitan H.S.

Reputation: 430

any equivalent to VB.net function name as return value in C#?

In vb.net there is a weird approach that you can use the function name as the result variable..

example:

Function Foo(ByVal bar As Integer) As List(Of Integer)
    Foo = New List(Of Integer)
    Foo.Add(bar + 1)
End Function

As far as i know, in C# you have to:

List<int> foo(int bar) 
{
     var result = new List<int>();
     result.Add(bar + 1);
     return result;
}

I'm not sure if it's by design or i just don't know the right way to do this.. Please enlight me!

Thanks in advance, Eitan.

Upvotes: 3

Views: 1927

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

C# doesn’t support that. On a historical note, the only reason for VB to support this is that previous (pre-.NET) versions used the function name assignment exclusively – i.e. didn’t have a Return statement.1

There’s a general consensus among .NET developers that you should use the Return … method even in VB rather than using FunctionName = … and Exit Function.


1 Well actually they did but it did something else.

Upvotes: 4

LightStriker
LightStriker

Reputation: 21004

As far as I know, there is no C# equivalent. However, it is only sugar syntax in VB, as under the hood, the function name is replaced by return behavior anyway.

The readability of using function name as return param is highly debatable. Most don't like it.

return also offer an advantage that function name doesn't have, resolving the method at that specific place.

Upvotes: 1

Related Questions