Skip to content

Commit 278349e

Browse files
VB -> C#: Make strings verbatim if it'd save escaping some characters
1 parent 4d54391 commit 278349e

2 files changed

Lines changed: 16 additions & 12 deletions

File tree

ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,16 @@ static Dictionary<string, VariableDeclarationSyntax> SplitVariableDeclarations(V
8585

8686
internal static ExpressionSyntax GetLiteralExpression(object value, string valueText = null)
8787
{
88-
if (value is string)
89-
return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal((string)value));
88+
if (value is string s) {
89+
var worthBeingAVerbatimString = s.IndexOfAny(new[] { '\r', '\n', '\\' }) > -1;
90+
if (worthBeingAVerbatimString) {
91+
var valueWithReplacements = s.Replace("\"", "\"\"");
92+
valueText = $"@\"{valueWithReplacements}\"";
93+
}
94+
return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
95+
SyntaxFactory.Literal(valueText, s));
96+
}
97+
9098
if (value == null)
9199
return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
92100
if (value is bool)

Tests/CSharp/ExpressionTests.cs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,20 @@ namespace CodeConverter.Tests.CSharp
44
{
55
public class ExpressionTests : ConverterTestBase
66
{
7-
[Fact(Skip = "Not implemented!")]
7+
[Fact]
88
public void MultilineString()
99
{
10-
TestConversionVisualBasicToCSharp(@"Class TestClass
10+
// Don't auto-test comments, otherwise it tries to put a comment in the middle of the string, which obviously isn't a valid place for it
11+
TestConversionVisualBasicToCSharpWithoutComments(@"Class TestClass
1112
Private Sub TestMethod()
12-
Dim x = ""Hello,
13+
Dim x = ""Hello\ All strings in VB are verbatim """" < that's just a single escaped quote
1314
World!""
1415
End Sub
15-
End Class", @"using System;
16-
using System.Collections.Generic;
17-
using System.Linq;
18-
using Microsoft.VisualBasic;
19-
20-
class TestClass
16+
End Class", @"class TestClass
2117
{
2218
private void TestMethod()
2319
{
24-
var x = @""Hello,
20+
var x = @""Hello\ All strings in VB are verbatim """" < that's just a single escaped quote
2521
World!"";
2622
}
2723
}");

0 commit comments

Comments
 (0)