How to copy string in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s1 = "a new day";
                string s2 = string.Copy(s1);

                Console.WriteLine(s1); // a new day
                Console.WriteLine(s2); // a new day

                Console.WriteLine(object.ReferenceEquals(s1, s2)); // False
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:

a new day
a new day
False

*/


answered Mar 21, 2015 by avibootz
edited Mar 21, 2015 by avibootz
0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s1 = "a new day";
                string s2 = s1;

                Console.WriteLine(s1); // a new day
                Console.WriteLine(s2); // a new day

                // s1 and s2 point to the same place in memeory

                Console.WriteLine(object.ReferenceEquals(s1, s2)); // True
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:

a new day
a new day
True

*/


answered Mar 21, 2015 by avibootz
edited Mar 21, 2015 by avibootz
...