Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply method to literal

Tags:

vb.net

linqpad

I am familiar with C#, but not at all with VB and I want to convert a C# example (in LINQPad) into VB:

if (2 + 2 == 4)
    "True".Dump();

I came up with the following working VB code:

Dim word = "True"
If 2 + 2 = 4 Then
    word.Dump
End If

Now, why could I not just write the following instead ?

If 2 + 2 = 4 Then
    "True".Dump  ' BC30035 Syntax error
End If

It seems like I cant apply a method to a litteral in VB and I must store it in a variable prior, but surely I must be missing something here... no ?

P.S. Parentheses around the string are not working any better.

like image 813
Frederic Avatar asked Dec 08 '25 10:12

Frederic


1 Answers

The issue is not that you cannot call a method on a literal. The issue is you cannot begin a line of code with a literal, much as you cannot begin a line of code with the New keyword. If you do this:

Dim x = "Hello".Split("l"c)
Dim y = 2.ToString()

it works without issue. If you do this:

"Hello".Split("l"c)
2.ToString()

you get two errors and, in both cases, mousing over the issue tells you:

Only member access expression can start an invocation statement.

Just as if you wanted to start a line with a constructor, you can use the Call keyword to effectively do what you want:

Call "Hello".Split("l"c)
Call 2.ToString()
like image 170
jmcilhinney Avatar answered Dec 10 '25 00:12

jmcilhinney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!