Independence Day Sale! Unlock 40% OFF on All Job-Oriented Training Programs – Limited Time Only! Offer Ending in
D
H
M
S
Get Now

C# String

04 Jul 2025
Beginner
1.72K Views
21 min read
Learn with an interactive course and practical hands-on labs

Best Free C# Course: Learn C# In 21 Days

C# string is a sequence of characters used to represent text. They are immutable and are defined by using the keyword string, which is an alias for System.String class commonly used in applications that involve text processing, user input, file I/O, and data formatting. Understanding string immutability, memory management, and built-in methods is crucial for writing efficient, secure, and high-performance applications.

In this C# tutorial, I'll break down the key concepts of working with strings, common methods for string manipulation, and why mastering them is essential for building high-performing, reliable applications. Let's dive in !

What is the C# string?

Strings in C# are a fundamental part of any application, playing a vital role in storing, handling, and manipulating text data. Whether you’re building a console app, a web application, or an enterprise system, working with strings is essential for tasks like user input, logging, file processing, and displaying messages.

string in C#

Some points to remember :
  • In C#, a string is a data type that stores character sequences such as words or sentences.
  • It is immutable, which means that once produced, the string's value cannot be modified, and any modification causes a new string to be formed.
  • Strings are often used to handle text and may be readily modified with the.NET framework's built-in functions.

Why Strings in C# Matters?

Mastering strings in C# will help you with the following:-

  • Write clean and efficient code.
  • Avoid memory and performance issues related to excessive string operations.
  • Understand key concepts like immutability, garbage collection, and reference behavior.
  • Build applications that handle text input/output in a global, scalable, and secure way.

Key Characteristics of Strings

Here are the key characteristics of strings in C#:

1. Immutable

  • Strings cannot be changed after creation. Modifying a string creates a new one.

2. Reference Type

  • Strings are objects (reference types) from the System.String class and stored in the heap.

3. Supports Indexing

  • You can access individual characters using index notation (str[0]).

4. Concatenation & Interpolation

  • Strings can be combined using +, +=, or $"Hello {name}" for interpolation.

5. Case-Sensitive Comparison

  • String comparisons are case-sensitive by default ("Hello" != "hello").

6. Built-in Methods

  • C# provides useful methods like .Length, .ToUpper(), .Substring(), etc.

Example of Strings in C#

 
using System;
class Program
{
    static void Main()
    {
        string message = "Hello, World!";
        Console.WriteLine(message);
    }
}

Output :

 Hello, World!

Explanation:

string message = "Hello, World!";
  • A string variable named message is declared and initialized.
  • Console.WriteLine(message); → Prints the string to the console. This is the most basic way to declare and use a string in C#.

Real-world Analogy

C# strings are similar to printed book pages. Once printed, the words on the page cannot be changed immediately. If you need to alter something, you must print a new page with the changes.

Explanation

  • The original string is like a book page.
  • Modifying the string creates a whole new page, just as modifications to a C# string create a new string.

    String vs. System.String

    In C#, string is an alias for System.String. They are functionally the same, but understanding this distinction can help clarify the language's syntax and structure.

    FeaturestringSystem.String
    TypeC# keyword(alias).Net class in System namespace
    UsageCommon in C# code (string name)Fully qualified name (System.Stringname;)
    Examplestring name = "Hello, World!";System.String name = "Hello, World!";
    Preferred forSimplicity and readabilityWhen using reflection or full namespace

    Immutability of String Objects

    • Strings in C# are immutable, meaning that once a string object is created, it cannot be altered.
    • This feature has implications for memory management and performance.
    • When you manipulate strings, a new string object is created instead of modifying the original.

      Properties of the String Class

      The String class has several key properties :

      Creating a String Object

      Methods of Creating Strings

      MethodDescriptionExample
      From a LiteralDefine a string directly using double quotes.string str = "Hello World";
      Using ConcatenationCombine multiple strings using the + operator.string fullName = "FirstName" + " LastName";
      Using ConstructorCreate a string from a character array using new string().char[] chars = { 'H', 'i' }; string str = new string(chars);
      Using Property or MethodUse a property or call a method that returns a string.string date = DateTime.Now.ToString();
      Using String FormattingUse interpolation or String.Format() to construct stringsstring msg = $"Hello, {name}"; String.Format("Age: {0}", age);

      Create a string from a literal

      This is the most common way to create a string. You define a string variable and assign the value within double quotes. You can use any type of characters within double quotes except some special characters like a backslash (\).

      Example: To illustrate the string creation using literals

      
      // C# program to demonstrate the
      // string creation using literals
      using System;
      
      class Program {
          static void Main(string[] args) {
              string str1 = "Hello, World!";
              Console.WriteLine(str1);
              
              // Using double slash to escape
              string str2 = "C:\\Users\\Amit\\Documents\\file.txt";
              Console.WriteLine(str2);
          }
      }
      

      Output

      
      Hello, World!
      C:\Users\Amit\Documents\file.txt
          

      Explanation

      • This C# program shows how to build strings from literals.The str1 variable contains the basic string "Hello, World!" which is printed directly.
      • The str2 variable demonstrates the usage of escape sequences (double backslashes \\) to indicate a file path, ensuring that special characters such as backslashes are appropriately handled.

        Create a string using concatenation

        You can create a string by using the string concatenation operator + in C#. This operator combines one or more strings.

        Example: To illustrate the use of the string concatenation operator

        
        // C# program to demonstrate the use of
        // the string concatenation operator
        using System;
        
        class Program {
            public static void Main() {
                string firstName = "Amit";
                string lastName = "Kumar";
                
                // Using concatenation operator
                string fullName = firstName + " " + lastName;
                Console.WriteLine(fullName);
            }
        }
        

        Output

        
        Amit Kumar
            

        Explanation

        • This C# program explains the string concatenation operator (+).
        • It combines two string variables, firstName and lastName, with a space between them to form a full name, which is then written to the console as "Amit Kumar".

          Create a string using a constructor

          The String class has several overloaded constructors that take an array of characters or bytes. You can create a string from a character array.

          Example: To illustrate the creation of a string using the constructor

          
          // C# program to demonstrate the creation 
          // of string using the constructor
          using System;
          
          class Program {
              public static void Main() {
                  char[] chars = { 'A', 'M', 'I', 'T' };
                  
                  // Create a string from a character array.
                  string str1 = new string(chars);
                  Console.WriteLine(str1);
              }
          }
          

          Output

          
          AMIT
              

          Explanation

          • This C# programshows how to create a string using the String constructor.
          • It generates a string from a character array of chars that contains individual characters ('A', 'M', 'I', and 'T').
          • The resulting string, "AMIT," is then displayed on the console.

          Create a string using a property or a method

          You can create a string by retrieving a property or calling a method that returns a string. For example, using methods of the String class to extract a substring from a larger string.

          Example: To illustrate the creation of a string using a property or a method

          
          // C# program to extract a substring from a larger
          // string using methods of the String class
          using System;
          
          class Program {
              public static void Main() {
                  string sentence = "Amit Kumar Singh";
                  
                  // Extracting a substring
                  string firstName = sentence.Substring(0, 4);
                  Console.WriteLine(firstName);
              }
          }
          

          Output

          
          Amit
              

          Explanation

          • This C# program shows how to extract a substring from a bigger string by calling the String class's Substring function.
          • In this example, the program extracts the first four characters ("Amit") of the text "Amit Kumar Singh" and displays the result on the console.

            Create a string using formatting

            The String.Format method is used to convert values or objects to their string representation. You can also use string interpolation to create strings.

            Example: To illustrate the creation of a string using the format method

            
            // C# program to demonstrate the creation of string using format method
            using System;
            
            class Program {
                public static void Main() {
                    int age = 25;
                    string name = "Amit";
                    
                    // String creation using string.Format method
                    string str = string.Format("{0} is {1} years old.", name, age);
                    Console.WriteLine(str);
                }
            }
            

            Output

            
            Amit is 25 years old.
                

            Explanation

            • This C# programexplains the use of a string.
            • The Format method generates a formatted string.
            • In this example, the computer inserts the values of the variable's name and age into a sentence, yielding the output "Amit is 25 years old."]
            • This demonstrates how to dynamically format strings based on variable values.

            Common String Methods

            Length of a String

            • You can find the length of a string using the Length property.

            Join Two Strings

            • Use the String.Concat or String.Join methods to concatenate strings.

            Compare Two Strings

            • You can compare two strings using the String.Compare method.

            Contains

            • Check if a substring exists within a string using the Contains method.

            Getting a Substring

            • Use the Substring method to extract a part of a string.

            String Escape Sequences

            • Special characters can be included in strings using escape sequences. For example, use \" for quotes and \\ for a backslash.

            String Interpolation

            • String interpolation allows you to embed expressions within string literals, making it easier to format strings.

               Common String Methods in C#

              In this example, we will practically apply the string methods we discussed above. We'll create strings, check their lengths, concatenate them, compare two strings, verify if one contains another, extract parts of strings, and use string interpolation. We'll also demonstrate handling special characters with escape sequences. This will provide a concise overview of working with strings in C#.

              Example

              using System;
              
              class Program {
                  public static void Main() {
                      // Creating strings
                      string firstName = "Amit";
                      string lastName = "Kumar";
                      
                      // 1. Length of a String
                      int length = firstName.Length;
                      Console.WriteLine($"Length of '{firstName}': {length}"); // Output: Length of 'Amit': 4
              
                      // 2. Join Two Strings
                      string fullName = String.Concat(firstName, " ", lastName);
                      Console.WriteLine($"Full Name: {fullName}"); // Output: Full Name: Amit Kumar
              
                      // 3. Compare Two Strings
                      int comparisonResult = String.Compare(firstName, lastName);
                      Console.WriteLine($"Comparison Result (firstName vs lastName): {comparisonResult}"); // Output: Negative, since 'Amit' is less than 'Kumar'
              
                      // 4. Contains
                      bool contains = fullName.Contains("Amit");
                      Console.WriteLine($"Does fullName contain 'Amit'? {contains}"); // Output: True
              
                      // 5. Getting a Substring
                      string subString = fullName.Substring(0, 4);
                      Console.WriteLine($"Substring of fullName (first 4 chars): {subString}"); // Output: Substring of fullName (first 4 chars): Amit
              
                      // 6. String Escape Sequences
                      string filePath = "C:\\Users\\Amit\\Documents\\file.txt";
                      Console.WriteLine($"File Path: {filePath}"); // Output: File Path: C:\Users\Amit\Documents\file.txt
              
                      // 7. String Interpolation
                      string greeting = $"Hello, {firstName} {lastName}!";
                      Console.WriteLine(greeting); // Output: Hello, Amit Kumar!
                      
                      // 8. Immutability of String Objects
                      firstName = "Raj"; // This does not change the original string; it creates a new string instead
                      Console.WriteLine($"New firstName: {firstName}"); // Output: New firstName: Raj
                  }
              }
              

              Output

              Length of 'Amit': 4
              Full Name: Amit Kumar
              Comparison Result (firstName vs lastName): -1 (or any negative number, because 'Amit' is lexicographically less than 'Kumar')
              Does fullName contain 'Amit'? True
              Substring of fullName (first 4 chars): Amit
              File Path: C:\Users\Amit\Documents\file.txt
              Hello, Amit Kumar!
              New firstName: Raj
              

              Explanation

              • This C# program demonstrates a variety of string techniques and ideas.
              • It covers string creation, length computation, and concatenation using String.
              • Concatenation and comparison of two strings using String.
              • Compare and use Contains to check for substrings, Substring to extract substrings, handle escape sequences, string interpolation, and string immutability.
                  Summary

                  C# strings are an important data type for managing and manipulating text in applications. They are immutable, which means that once generated, they cannot be changed, affecting memory management and performance. This article explores various ways to create strings, including using literals, concatenation, constructors, and formatting techniques, along with common string methods and properties. Understanding how C# strings work is essential for effective text processing and robust application development.

                  Enroll in the C # Full Course for Free to master string manipulation and other essential C# concepts!

                  FAQs

                  In C#, strings are used to represent character sequences such as words, sentences, or any other type of text. They are essential for working with text data because they include built-in manipulation capabilities such as concatenation, comparison, and formatting. C# strings are immutable, which means they cannot be modified once created.

                  A C# string is immutable because, once generated, a string object's value cannot be changed. This architecture assures thread safety, decreases memory fragmentation, and improves efficiency by allowing string objects to be reused via methods such as string interning.

                  Yes, in C#, a string can be null, which means it does not relate to any object in memory. A null string differs from an empty string ("") in that it signifies the absence of a value, whereas an empty string is a legitimate string containing zero characters.

                  In C#, the string can be used to determine whether a string is null or empty.The isNullOrEmpty method. This function returns true if the string is either null or empty (""). You may also use the string to determine whether or not a string has any whitespace.The IsNullOrWhiteSpace method returns true for strings that are null, empty, or only include whitespace.

                  A string in C# represents and manipulates sequences of characters, such as text. Strings are essential for interpreting user input, displaying messages, processing data, and performing operations such as concatenation, comparison, and searching. They allow developers to work efficiently with textual data in apps.

                  In C#, strings are saved as System objects.String class in heap memory. Each string is stored as an array of characters, and because strings are immutable, any change to a string generates a new instance in memory rather than modifying the original. This approach optimizes memory management and ensures that strings remain constant throughout their use in apps.

                  Take our Csharp skill challenge to evaluate yourself!

                  In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

                  GET FREE CHALLENGE

                  Share Article
                  About Author
                  Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

                  Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

                  Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
                  Live Training - Book Free Demo
                  .NET Solution Architect Certification Training
                  24 Aug
                  10:00AM - 12:00PM IST
                  Checkmark Icon
                  Get Job-Ready
                  Certification
                  Software Architecture and Design Training
                  24 Aug
                  10:00AM - 12:00PM IST
                  Checkmark Icon
                  Get Job-Ready
                  Certification
                  Azure AI & Gen AI Engineer Certification Training Program
                  28 Aug
                  08:30PM - 10:30PM IST
                  Checkmark Icon
                  Get Job-Ready
                  Certification
                  Advanced Full-Stack .NET Developer with Gen AI Certification Training
                  31 Aug
                  08:30PM - 10:30PM IST
                  Checkmark Icon
                  Get Job-Ready
                  Certification
                  Java Solution Architect Certification Training
                  31 Aug
                  05:30PM - 07:30PM IST
                  Checkmark Icon
                  Get Job-Ready
                  Certification
                  Accept cookies & close this