Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between a mutable and immutable string in C#?
Mutable string
StringBuilder is a mutable string in C#. With StringBuilder, you can expand the number of characters in the string. The string cannot be changed once it is created, but StringBuilder can be expanded. It does not create a new object in the memory.
Set StringBuilder −
StringBuilder str = new StringBuilder();
Let us see an example to learn how to work with StringBuilder in C# −
Example
using System;
using System.Text;
public class Program {
public static void Main() {
StringBuilder str = new StringBuilder("Web World!!",30);
str.Replace("World", "Arena");
Console.WriteLine(str);
}
}
Output
Web Arena!!
Immutable string
Immutable string is a String in C#. A new memory is created every time. A String cannot be changed once it is created, unlike StringBuilde. It does not create a new object in the memory.
Set a string −
String str = “tim”;
The following is an example of a string in which we are comparing two string −
Example
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str1 = "Steve";
string str2 = "Ben";
if (String.Compare(str1, str2) == 0) {
Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
} else {
Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
}
Console.ReadKey() ;
}
}
}
Output
Steve and Ben are not equal strings.
Advertisements