C# strings can be seen as a collection of characters. A string can be of length 1 (one character), but its usually longer. A string is always written in double qoutes.

This means a string variable in C# can hold text: words, sentences, books. Programming languages have variables.

Variables have a data type. A variable can be of the data type string.
If you write string str1 = "This";. Then string is the data type of variable str1.

String example

String variable

In the example below we use C# to print text. The only line that outputs text to the screen is Console.WriteLine(). The semicolon ; is necessary at the end of each statement.

First define a string variable str1, then print the variable Console.WriteLine(str1);.

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;

namespace ExampleApplication {

class ExampleProg {

static void Main(string[] args) {
string str1 = "This is string variable";
Console.WriteLine(str1);
Console.ReadKey() ;
}
}
}

Multiple lines

Generally there are 2 ways to print multiple lines.

  • Method 1. call display function x times Console.WriteLine(). Not Console.Write(), which doesn’t add a newline.
  • Method 2. use the newline character inside the string. This is written as \n, but is one character.

Both of these are common in programming.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;

namespace ExampleApplication {

class ExampleProg {

static void Main(string[] args) {
string str1 = "This is string variable";

// method 1: function calls
Console.WriteLine(str1);
Console.WriteLine(str1);

// method 2: newline character
Console.WriteLine("Line 1\nLine 2\n");

Console.ReadKey() ;
}
}
}

$mcs *.cs -out:main.exe
$mono main.exe
This is string variable
This is string variable
Line 1
Line 2

Exercises

  1. Create a program with multiple string variables
  2. Create a program that holds your name in a string.