C# String

In C#, a string is used to store text. It represents a sequence of characters and is one of the most commonly used reference types.

Strings in C# are immutable, which means their value cannot be changed once created.

Creating Strings


// String declaration
string name = "Rahul";
string message = "Welcome to C#";
    

Common String Methods

Method Description Example
Length Returns string length name.Length
ToUpper() Converts to uppercase name.ToUpper()
ToLower() Converts to lowercase name.ToLower()
Trim() Removes extra spaces name.Trim()
Substring() Extracts part of string name.Substring(0, 3)
Replace() Replaces text message.Replace("C#", "DotNet")
Contains() Checks text existence message.Contains("C#")

Example


string text = "  Hello World  ";

Console.WriteLine(text.Length);
Console.WriteLine(text.Trim());
Console.WriteLine(text.ToUpper());
Console.WriteLine(text.Substring(2, 5));
    

String Concatenation

Combining strings together.


string firstName = "Rahul";
string lastName = "Sharma";

string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
    

String Interpolation

A cleaner way to format strings using $.


int age = 25;
Console.WriteLine($"My age is {age}");
    

Key Points

  • Strings are reference types
  • Strings are immutable
  • Rich set of built-in methods
  • String interpolation improves readability

Conclusion

Strings play a vital role in handling text data in C#. Understanding string methods and formatting techniques helps in writing clean and efficient code.

C# String Quiz

Q1. What does string.Length return?



Q2. Which method removes spaces?



Q3. Which symbol is used in string interpolation?


C# Introduction C# Variables & Keywords C# Data Types C# If Else Statement C# Loops C# Comments C# Type Casting C# User Input C# Operators C# Math C# String C# OOP Concepts C# Classes and Objects C# Multiple Classes and Objects C# Class Members C# Constructors C# Access Modifiers