1

In Ruby, I can put multiple statements in a interpolated string, eg.

puts "#{a = 1; b = 2; a + b;}"

Or I can put them in multiple lines like this:

puts "#{a = 1;
b = 2;
a + b;}"

Can I do the same thing in C# 6? I've tried but failed. Below is my C# code.

Console.WriteLine($@"haha
{int a = 1;
 int b = 2;
 a+b;}
heihei");

When I try to run the C# program, I got:

CS1525 Invalid expression term 'int'
CS1073 Unexpected token 'a'

I hope someone can help.

7
  • You're asking 2 different questions at once... Commented Dec 1, 2015 at 7:42
  • I'm not sure I've what you mean. But I think you can simply use @ Like this: Console.WriteLine($@"haha {int a = 1; int b = 2; a+b;} heihei"); Commented Dec 1, 2015 at 7:42
  • @i3arnon Looks like one to me. What's the second one? Commented Dec 1, 2015 at 7:43
  • 1
    @Rob 1. Multiple statements - not possible. 2. Multiline - possible. Commented Dec 1, 2015 at 7:43
  • @i3arnon, Haha, thanks. I got it now. Commented Dec 1, 2015 at 7:47

2 Answers 2

4

You can't have full code blocks in your string interpolation statements. You can only do evaluations inside.

So this works (pulled the variables outside):

int a = 1;
int b = 2;
Console.WriteLine($@"haha
{a+b}
heihei");

And this too (do evaluation only):

Console.WriteLine($@"haha
{1+2}
heihei");
Sign up to request clarification or add additional context in comments.

Comments

0

Ruby is different then C# in your case you write full code in your string interpolation so it's not working.

Console.WriteLine($"Name = {name}, hours = {hours:hh}")

or

Console.WriteLine($@"haha {1+2} heihei");

For Ref: Microsoft C#

Comments

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.