How to Prove Immutabiltiy of String in C#?

后端 未结 2 659
灰色年华
灰色年华 2021-02-08 11:06

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# str

2条回答
  •  花落未央
    2021-02-08 11:18

    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

    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/

提交回复
热议问题