Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# Strings

In C#, a string is a series of characters that is used to represent text. It can be a character, a word or a long passage surrounded with the double quotes ". The following are string literals.

Example: String Literals
"S"
"String"
"This is a string."

C# provides the String data type to store string literals. A variable of the string type can be declared and assign string literal, as shown below.

Example: String Type Variables
string ch = "S";
string word = "String";
string text = "This is a string.";
Try it

The maximum size of a String object in memory is 2GB or about 1 billion characters. However, practically it will be less depending upon CPU and memory of the computer.

There two ways to declare a string variable in C#. Using System.String class and using string keyword. Both are the same and make no difference. Learn string vs String for more info.

Example: String and string
string str1 = "Hello"; // uses string keyword
 
String str2 = "Hello"; // uses System.String class
Try it

In C#, a string is a collection or an array of characters. So, string can be created using a char array or accessed like a char array.

Example: String as char Array
char[] chars = {'H','e','l','l','o'};

string str1 = new string(chars);  
String str2 = new String(chars); 

foreach (char c in str1)
{
    Console.WriteLine(c);
}
Try it

Special Characters

A text in the real world can include any character. In C#, because a string is surrounded with double quotes, it cannot include " in a string. The following will give a compile-time error.

Example: Invalid String
string text = "This is a "string" in C#.";

C# includes escaping character \ (backslash) before these special characters to include in a string.

Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.

Example: Escape Char \
string text = "This is a "string" in C#.";
string str = "xyzdef\rabc";
string path = "\\mypc\ shared\project";
Try it

Verbatim Strings

It is tedious to prefix \ to include every special characters. Verbatim string in C# allows a special characters and line brakes. Verbatim string can be created by prefixing @ symbol before double quotes.

Example: Escape Sequence
string str = @"xyzdef
abc";
string path = @"\mypcsharedproject";
string email = @"[email protected]";
Try it

The @ symbol can also be used to declare a multi-line string.

Example: Multi-line String
string str1 = "this is a 
" + 
        "multi line 
" + 
        "string";
		
// Verbatim string
string str2 = @"this is a 
        multi line 
        string";
Try it

Please note that you cannot use a backslash to allow " in a varbatim string. If you wish to include @, then use double double-quotes "" to include " in a verbatim string.

string text = "This is a "string" in C#."; // valid
string text = @"This is a "string." in C#."; // error
string text = @"This is a "string" in C#."; // error
string text = @"This is a ""string"" in C#."; // valid

String Concatenation

Multiple strings can be concatenated with + operator.

Example: String Concatenation
string name = "Mr." + "James " + "Bond" + ", Code: 007";
 
string firstName = "James";
string lastName = "Bond";
string code = "007";
 
string agent = "Mr." + firstName + " " + lastName + ", Code: " + code;
Try it

A String is immutable in C#. It means it is read-only and cannot be changed once created in the memory. Each time you concatenate strings, .NET CLR will create a new memory location for the concatenated string. So, it is recommended to use StringBuilder instead of string if you concatenate more than five strings.

String Interpolation

String interpolation is a better way of concatenating strings. We use + sign to concatenate string variables with static strings.

C# 6 includes a special character $ to identify an interpolated string. An interpolated string is a mixture of static string and string variable where string variables should be in brackets.

Example: String Interpolation
string firstName = "James";
string lastName = "Bond";
string code = "007";
 
string fullName = $"Mr. {firstName} {lastName}, Code: {code}";
Try it

In the above example of interpolation, $ indicates the interpolated string, and includes string variable to be incorporated with a string.

Use two braces, {{ or }} to include { or } in a string.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.