Even Mien
Even Mien

Reputation: 45918

What is the syntax for initializing a string with a block of text in .NET?

I'm writing a unit test and can't remember the syntax for initializing a string with a large block of formatted text.

string _testData = "a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";

Upvotes: 2

Views: 1539

Answers (5)

Josh E
Josh E

Reputation: 7432

I agree with Wayne Hartman - just store your large text as a text file and read that into a string for the test, e.g.:

 string testData = File.ReadAllText(fileToRead);
    //Unit test using the testData

There isn't really any logic here that would get in the way of the rest of your test. The Unit Test still focuses on your functionality, it just uses the text file to conveniently store the large string.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501606

As others have said, it's

    string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";

This is called a verbatim string literal. The other effect is that backslash is no longer used to escape anything - which makes it useful for regular expressions and Windows file paths.

Double quotes are achieved by doubling. For instance to get x"y in a string:

string verbatim = @"x""y";
string regular = "x\"y";

Upvotes: 6

Scott Ivey
Scott Ivey

Reputation: 41568

use the @ literal to denote string types.

string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";

From MSDN: "Verbatim string literals start with @ and are also enclosed in double quotation marks. The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name. To include a double quotation mark in an @-quoted string, double it."

Upvotes: 10

Wayne Hartman
Wayne Hartman

Reputation: 18477

Instead of cluttering up your code with static, formatted text, perhaps you should create a file resource that your application reads from and stores in memory. This way, should you need to change it or format a different way, you can make the change without further touching and cluttering up your code.

Upvotes: 1

Adam Robinson
Adam Robinson

Reputation: 185653

Add an @ before the literal.

string _testData = @"a couple screens worth of text data here
and I need to preserve the formatting
such as line breaks,
etc.";

Upvotes: 15

Related Questions