Variables and strings in C#

This tutorial explains how to create variables and use strings in the C# programming language. Variables are used to store data that can be used throughout a program.

Variables can store data of different types. One data type is the string. Strings can contain characters such as letters, numbers or symbols. Strings can be a single character, a bunch of mixed characters, words, or sentences.

Other data types include integers (whole numbers eg. 4), floats, (numbers with decimal place eg. 3.56), and Booleans (true or false values). There are other data types that exist but these are the main ones we will start with. In this tutorial we will focus on strings and how they can be used in variables and statements.

When you create a variable you must declare its data type (eg. string), give it a name (eg. age, score, name), and then you can assign it a value. For example,  look at the following statement:

string firstName = "Joe";

The statement above would create a new variable called firstName of the string data type containing the value Joe. Strings are always contained inside single or double quotes.

Watch the video below and then scroll down to see the sample code.

Sample C# code

The code below contains comments to explain each statement.

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("What is your name?"); // this displays a message in console
      string message = "Hello there, "; // creates a string variable that contains a message
      string name = Console.ReadLine (); // creates a string that stores the user's name from input
      Console.WriteLine (message + name); // writes the message and name to the console
    }
  }
}

Next tutorial: Integers and floats in C#