Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Prove Immutabiltiy of String in C#?

In my last c# interview,
I was asked to prove immutability of C# string,I know what is meant by immutability of c# string,But is it possible to prove immutability of c# string through code ? can i have a sample code snippet please. Thanks in advance

like image 962
BinaryOf Sam Avatar asked May 16 '16 11:05

BinaryOf Sam


People also ask

How do you prove a string is immutable in C#?

Strings and Immutability In the C# programming language, you can declare a string and print out its value as follows: 1string str = "Hello World"; 2Console. WriteLine(str); 3//This will print out "Hello World" to the console. When you create a string, it is immutable.

How string is immutable explain with example?

Let's understand the concept of immutable through an example. In the string constant pool, the Hello remains unchanged, and a new string object is created with HelloWorld. It shows that the strings are immutable. The reference variable points to the Hello not to the HelloWorld.

What is an immutable string How can we modify such a string?

There is a term called immutable, which means the state of an object can't be changed after is has been created. A string is an immutable type. The statement that a string is immutable means that, once created, it is not altered by changing the value assigned to it.


2 Answers

Yes, It is possible to prove immutability of c# string using ObjectIDGenerator Class.

Following answer is taken from dotmob article on String Vs Stringbuilder in C#

Actually ObjectIDGenerator will return an unique integer value for instances that we created in our programs.With the help of this class we can check whether new instance is created or not for various operations on string and stringbuilder .Consider following program

using System;
using System.Text;
using System.Runtime.Serialization;

class Program
{
  static void Main(string[] args)
  {
    ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    bool blStatus = new bool();
    //just ignore this blStatus Now.
    String str = "My first string was ";
    Console.WriteLine("str = {0}", str);
    Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
    //here blStatus get True for new instace otherwise it will be false
    Console.WriteLine("this instance is new : {0}\n", blStatus);
    str += "Hello World";
    Console.WriteLine("str = {0}", str);
    Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
    Console.WriteLine("this instance is new : {0}\n", blStatus);
    //Now str="My first string was Hello World"
    StringBuilder sbr = new StringBuilder("My Favourate Programming Font is ");
    Console.WriteLine("sbr = {0}", sbr);
    Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
    Console.WriteLine("this instance is new : {0}\n", blStatus);
    sbr.Append("Inconsolata");
    Console.WriteLine("sbr = {0}", sbr);
    Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
    Console.WriteLine("this instance is new : {0}\n", blStatus);
    //Now sbr="My Favourate Programming Font is Inconsolata"
    Console.ReadKey();
  }
}

Output Will look like this enter image description here

Instance id for string get changed from 1 to 2 when str concatenated with “Hello World”.while instance id of sbr remains same as 3 after append operation also. This tells all about mutability and immutability. blStatus variable indicate whether the instance is new or not.

You can find complete article on the topic from : http://dotnetmob.com/csharp-article/difference-string-stringbuilder-c/

like image 139
Shamseer K Avatar answered Sep 22 '22 03:09

Shamseer K


I can prove that a string is not immutable. All I need to do is to show some code which mutates a string, like so:

using System;
using System.Runtime.InteropServices;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            const string test = "ABCDEF"; // Strings are immutable, right?
            char[] chars = new StringToChar {str = test}.chr;
            chars[0] = 'X';

            // On an x32 release or debug build or on an x64 debug build, 
            // the following prints "XBCDEF".
            // On an x64 release build, it prints "ABXDEF".
            // In both cases, we have changed the contents of 'test' without using
            // any 'unsafe' code...

            Console.WriteLine(test);

            // The following line is even more disturbing, since the constant
            // string "ABCDEF" has been mutated too (because the interned 'constant' string was mutated).

            Console.WriteLine("ABCDEF");
        }
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct StringToChar
    {
        [FieldOffset(0)] public string str;
        [FieldOffset(0)] public char[] chr;
    }
}

Now whether this should be considered a bug in C# is a different matter. :) (The answer is probably that FieldOffset should be considered to be unsafe - the code above is purportedly safe and therefore the string should not be mutatable.)

Also, I think you could legitimately argue that string is immutable in spirit, even if there are silly edge cases which violate its immutability in supposedly safe code.

like image 43
Matthew Watson Avatar answered Sep 20 '22 03:09

Matthew Watson