0
0
CsharpHow-ToBeginner · 3 min read

How to Create String in C# - Simple Guide

In C#, you create a string by using the string keyword followed by a variable name and assigning it text inside double quotes, like string name = "Hello";. Strings are sequences of characters used to store text data.
📐

Syntax

To create a string in C#, use the string keyword, then the variable name, an equals sign, and the text inside double quotes. End the statement with a semicolon.

  • string: the type for text data
  • variable name: your chosen name for the string
  • =: assigns the text to the variable
  • "text": the actual text inside double quotes
  • ;: ends the statement
csharp
string greeting = "Hello, world!";
💻

Example

This example shows how to create a string variable and print it to the console.

csharp
using System;

class Program
{
    static void Main()
    {
        string message = "Welcome to C#!";
        Console.WriteLine(message);
    }
}
Output
Welcome to C#!
⚠️

Common Pitfalls

Common mistakes when creating strings include forgetting the double quotes, missing the semicolon, or using single quotes which are for characters, not strings.

Also, strings are immutable, so changing a string creates a new one instead of modifying the original.

csharp
string wrong = "Hello"; // Correct
string right = "Hello"; // Correct

char singleChar = 'H'; // Single quotes for single characters, not strings
📊

Quick Reference

ConceptDescription
stringType used to store text data
Double quotesText must be inside double quotes to be a string
SemicolonEnds the statement
ImmutableStrings cannot be changed after creation
Single quotesUsed for single characters, not strings

Key Takeaways

Use the string keyword and double quotes to create strings in C#.
Always end string declarations with a semicolon.
Strings are immutable; modifying them creates new strings.
Use single quotes only for single characters, not strings.
Forget double quotes or semicolons causes syntax errors.