Skip to main content

Why and how the C# strings are immutable? Explained with examples

C# strings are immutable, meaning that once a string object is created, its value cannot be changed. Instead, any operation that modifies a string, such as concatenation or replacement, creates a new string object with the modified value.

One reason for this immutability is that strings are often used as keys in dictionaries or as elements in collections, and immutable objects are more efficient for these uses because their hash code does not change.

Another reason is that strings are often used in multithreaded environments, and immutability allows multiple threads to access the same string object without the risk of data corruption. 


Example:

The string which is a reference type stored in a memory heap



Suppose we are creating a string str and assign a value  "a";

That will be stored in the memory location like this




Again if we assigning another value to the same string that is "b" 


This will not replace the existing value



Instead this will create another memory location like this 



This characteristics is called immutable

The memory will grow as you assign new values to the same string



As a memory management best practices if the string is involved in multiple value assignment it's better to use mutable string handle StringBuilder 

  

 In summary, C# strings are immutable because it is more efficient for their use cases and it allows them to be used in a safe way in multithreading scenarios.

 

This concept is also explained in a video here

Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven