159

Is there a way to have multiline strings in VB.NET like Python

a = """
multi
line
string
"""

or PHP?

$a = <<<END
multi
line
string
END;

Of course something that is not

"multi" & _
"line
Isaace96
  • 11
  • 5
pistacchio
  • 56,889
  • 107
  • 278
  • 420

21 Answers21

238

You can use XML Literals to achieve a similar effect:

Imports System.XML
Imports System.XML.Linq
Imports System.Core

Dim s As String = <a>Hello
World</a>.Value

Remember that if you have special characters, you should use a CDATA block:

Dim s As String = <![CDATA[Hello
World & Space]]>.Value

2015 UPDATE:

Multi-line string literals were introduced in Visual Basic 14 (in Visual Studio 2015). The above example can be now written as:

Dim s As String = "Hello
World & Space"

MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.

Details are added to the Roslyn New-Language-Features-in-VB-14 Github repository.

Community
  • 1
  • 1
Vincenzo Alcamo
  • 2,412
  • 1
  • 15
  • 2
  • how can you do variable replacements in there? like " a=" & someint & "," – Christopher Mahan Mar 30 '11 at 23:28
  • 1
    @Christopher - I typically find it more readable to put tokens in the string constant, and then replace them. So `s="... a=~someint~ ..."` and then `s=s.Replace("~someint~', SomeInt)`. – Herb Caudill Aug 17 '11 at 09:44
  • 1
    This doesn't appear to work with dynamic compilation: CodeDomProvider.CreateProvider("VisualBasic").CompileAssemblyFromFile(, <.vb file with above trick syntax in it>) ... Any ideas? Is this just VS 2010 syntactic sugar? – Chad Jun 04 '12 at 02:37
  • Amazing. It works with adding variables with <%=var>, without having to do all that ampersand nonsense. – The Phil Lee Nov 23 '13 at 00:38
  • Don't forget you'll have to escape your `<` characters with the fairly unreadable `<` unless you're willing to also [add a CDATA](http://stackoverflow.com/a/11954808/33080) (but then you can't embed stuff using<%= %>). – Roman Starkov Apr 24 '14 at 10:09
  • 1
    @romkyns Not true, I figured out how to use CDATA and still be able to embed using <%= %> See [here](http://stackoverflow.com/questions/706382/multiline-strings-in-vb-net/24087600#24087600) – Nelson Jul 02 '14 at 21:39
  • Brilliant. In my scenario I had to use .ToString() instead of .value to get the html code (my string contained html tags) – pkExec Jun 04 '15 at 11:00
  • It seems that the enhanced Intellisense of **Resharper** doesn't like the new syntax. It compiles fine, but I get ugly red highlighting and underlining :( – Jordan Rieger Aug 25 '15 at 18:07
  • 1
    Awesome! How do you maintain code indentation without introducing it into the literal under the newer syntax? – Panzercrisis Nov 22 '16 at 21:00
  • 1
    in case anyone else has the same issue - Roslyn apparently isn't enabled for Web Site project types in VS2015 and must be downloaded separately. See: http://blogs.msdn.com/b/webdev/archive/2014/05/12/enabling-the-net-compiler-platform-roslyn-in-asp-net-applications.aspx – Mike W Nov 07 '17 at 19:00
52

VB.Net has no such feature and it will not be coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. It has to do with removing the _ from a multi-line statement or expression. This does remove the need to terminate a multiline string with _ but there is still no mult-line string literal in VB.

Example for multiline string

Visual Studio 2008

Dim x = "line1" & vbCrlf & _
        "line2"

Visual Studio 2010

Dim x = "line1" & vbCrlf & 
        "line2"
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • So then how does it work for XML literals? Either it is possible, or XML literals are using a different technique - and if a different technique, then one that could be extended to multi-line strings. – mellamokb Aug 15 '13 at 20:04
  • 1
    @mellamokb XML literals are .. special for lack of a better word. The compiler understands them and hence will allow them to span multiple lines implicitly. No such support was added for multi-line strings. Adding such support is *much* easier than XML literals, it just didn't meet the bar for that release. – JaredPar Aug 15 '13 at 23:18
44

I used this variant:

     Dim query As String = <![CDATA[
        SELECT 
            a.QuestionID
        FROM 
            CR_Answers a

        INNER JOIN 
            CR_Class c ON c.ClassID = a.ClassID
        INNER JOIN
            CR_Questions q ON q.QuestionID = a.QuestionID
        WHERE 
            a.CourseID = 1
        AND 
            c.ActionPlan = 1
        AND q.Q_Year = '11/12'
        AND q.Q_Term <= (SELECT CurrentTerm FROM CR_Current_Term)
    ]]>.Value()

it allows < > in the string

Community
  • 1
  • 1
Andy
  • 2,124
  • 1
  • 26
  • 29
  • 1
    Great technique, but one may have to add some references to your project to make it work. See: https://msdn.microsoft.com/en-us/library/bb531455%28v=vs.90%29.aspx and http://stackoverflow.com/a/28654126/3175562 – Mike Sep 30 '15 at 14:58
41

Multi-line strings are available since the Visual Studio 2015.

Dim sql As String = "
    SELECT ID, Description
    FROM inventory
    ORDER BY DateAdded
"

You can combine them with string interpolation to maximize usefullness:

Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"

Dim sql As String = $"
    SELECT {primaryKey}, Description
    FROM {inventoryTable}
    ORDER BY DateAdded
"

Note that interpolated strings begin with $ and you need to take care of ", { and } contained inside – convert them into "", {{ or }} respectively.

Here you can see actual syntax highlighting of interpolated parts of the above code example:

enter image description here

If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.

Community
  • 1
  • 1
miroxlav
  • 11,796
  • 5
  • 58
  • 99
22

Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884

You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)

Dim multiline = "multi
line
string"

VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""

Lucian Wischik
  • 2,160
  • 1
  • 20
  • 25
  • 2
    Thank you Lucian for adding multi-line strings into the VB. Maybe you can update your answer, because VS 2015 is now RTM. And maybe you can also poke somebody in your company to update related [MSDN article](https://msdn.microsoft.com/en-us/library/vstudio/5chcthbw%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396). – miroxlav Aug 01 '15 at 09:14
16

this was a really helpful article for me, but nobody mentioned how to concatenate in case you want to send some variables, which is what you need to do 99% of the time.

... <%= variable %> ...

Here's how you do it:

<SQL> SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>' </SQL>.Value

Adam
  • 173
  • 1
  • 5
  • 18
    In this case, you want to avoid concatenation and instead use SQL parameters as they're better at hardening against SQL injection attacks. I can see this being useful for dynamic SQL generation, though (without passing along user input). – Chad Levy Jul 30 '13 at 01:51
10

Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:

 s="""this is gonna 
last quite a 
few lines"""

then do a:

  for i in s.split('\n'):
    print 'mySB.AppendLine("%s")' % i

#    mySB.AppendLine("this is gonna")
#    mySB.AppendLine("last quite a")
#    mySB.AppendLine("few lines")

or

  print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))

#    "this is gonna" & _ 
#    "last quite a" & _ 
#    "few lines"

then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey (fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.

roufamatic
  • 18,187
  • 7
  • 57
  • 86
RichardJohnn
  • 654
  • 9
  • 24
9

Multi-line string literals in vb.net using the XElement class.

Imports System.Xml.Linq

Public Sub Test()

dim sOderBy as string = ""

dim xe as XElement = <SQL>
                SELECT * FROM <%= sTableName %>
                 <ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
                 </SQL>

'** conditionally remove a section 
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove

'** convert XElement value to a string 
dim sSQL as String = xe.Value

End Sub
windchaser
  • 141
  • 1
  • 5
8

To me that is the most annoying thing about VB as a language. Seriously, i once wrote the string in a file and wrote code something along the lines of:

Dim s as String = file_get_contents("filename.txt")

just so i could test the query directly on SQL server if i need to.

My current method is to use a stored procedure on the SQL Server and just call that so i can pass in parameters to the query, etc

animuson
  • 53,861
  • 28
  • 137
  • 147
Osiname
  • 81
  • 1
  • 1
  • Maybe is a good idea to include in the project that with a .sql file extension (if Stored Procedures) are not introduced yet https://stackoverflow.com/questions/41860260/how-to-add-an-sql-file-to-resources-in-visual-studio#:~:text=Right%2Dclick%20your%20project%20in,Action%22%20to%20%22Embedded%20Resource%22 – federico Mar 17 '23 at 15:24
5

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value
Nelson
  • 2,040
  • 17
  • 23
3

Disclaimer: I love python. It's multi-line strings are only one reason.

But I also do VB.Net, so here's my short-cut for more readable long strings.

  Dim lines As String() = {
    "Line 1",
    "Line 2",
    "Line 3"
  }
  Dim s As String = Join(lines, vbCrLf)
3

You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with

 Dim a = My.Resources.Whatever_you_chose
habakuk
  • 2,712
  • 2
  • 28
  • 47
2

you can use XML for this like

dim vrstr as string = <s>
    some words
    some words
    some
    words
</s>
Jack Gajanan
  • 1,596
  • 14
  • 18
1

in Visual studio 2010 (VB NET)i try the following and works fine

Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>

dim Test1 as string =<a>onother multiline example</a>
user1166557
  • 43
  • 1
  • 7
1

Available in Visual Basic 14 as part of Visual Studio 2015 https://msdn.microsoft.com/en-us/magazine/dn890368.aspx

But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.

Bart VdA
  • 578
  • 1
  • 5
  • 15
0

If you need an XML literal in VB.Net with an line code variable, this is how you would do it:

<Tag><%= New XCData(T.Property) %></Tag>
Ori Samara
  • 71
  • 6
  • Note sure why you are mentioning an XML literal here, don't see XML mentioned in the original question. – Kmeixner Mar 03 '16 at 20:45
-1

Since this is a readability issue, I have used the following code:

MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text
Zac
  • 4,510
  • 3
  • 36
  • 44
  • 1
    This is bad. You just created 4 instances of string – T.S. Oct 26 '15 at 23:19
  • I inherited a legacy VB6 code I have to port to VB.NET which is full of these! :( In this case I prefer to sacrifice performance to maintain readability. – Zac Oct 27 '15 at 08:07
  • You don't have to. You always can concatenate without re-assigning a variable, and format within those lines – T.S. Oct 27 '15 at 12:49
  • In my case is not applicable to switch to the correct syntax as I should modify a full bunch of code and there is no time left on the project. – Zac Nov 09 '15 at 15:19
-1

You can also use System.Text.StringBuilder class in this way:

Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")

Then you get the multiline string using:

sValue.ToString()
ᗩИᎠЯƎᗩ
  • 2,122
  • 5
  • 29
  • 41
-2

Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.

Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)

It will show two identical MessageBoxes with 2 lines.

SimplyInk
  • 5,832
  • 1
  • 18
  • 27
LuizLoyola
  • 386
  • 3
  • 20
-9

No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)

Jason Irwin
  • 1,985
  • 2
  • 29
  • 42
-16

if it's like C# (I don't have VB.Net installed) you can prefix a string with @

foo = @"Multiline
String"

this is also useful for things like @"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.

Andy Hohorst
  • 381
  • 3
  • 11