3

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.

2
  • What is the question? You can use Return in VB.net Commented Nov 4, 2012 at 11:02
  • I'm asking about how to avoid declaring return variable on each function in C# Commented Nov 4, 2012 at 11:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

By previous versions, one means non .NET versions of Visual Basic (VB6 , VBScript and VBA).
@Oded LOL, in my mind “previous versions” is firmly VB6 even though we’ve long left VB7 behind us. Will fix.
1

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.

4 Comments

Yes, i did understood that.. but i'm trying to get my C# code sweeter (-:
@user1179861: If you want to make your C# sweeter, (or your VB) don't use function names. :)
@Oded: Code Dentists are always overpriced.
It's more than just syntactic sugar. With a return statement, the method returns immediately. When using the method name setter, it doesn't. And you can thus change the value several times before it hits the end of the method, such as in a loop, or whatever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.