Search code examples
c#uwp.net-core

How to do String.Copy in .net core?


In porting a .net framework app to .net core app, there are some uses of String.Copy to copy strings. But it looks this method is removed from .net core, so how would you copy a string in .net core app, and as a result, it is not present in uwp too. Does assignment string b = a; in .net core means something different as in .netframework?

The copy is used in this code:

public DataDictionary(DataDictionary src)
        :this()
    {
        this.Messages = src.Messages;
        this.FieldsByName = src.FieldsByName;
        this.FieldsByTag = src.FieldsByTag;
        if (null != src.MajorVersion)
            this.MajorVersion = string.Copy(src.MajorVersion);
        if (null != src.MinorVersion)
            this.MinorVersion = string.Copy(src.MinorVersion);
        if (null != src.Version)
            this.Version = string.Copy(src.Version);
    }

Solution

  • Assignment of a string is something else than creating a copy. a = b just sets the reference of both variables to the same memory segment. string.Copy actually copies the string and thus the references are not the same any more.

    I doubt however if you need string.Copy. Why would you want to have another reference? I can't think of any common cases you ever want this (unless you are using unmanaged code). Since strings are immutable, you can't just change the contents of the string, so copying is useless in that case.


    Given your update with the code that uses string.Copy, I would say it is not useful to use string.Copy. Simple assignments will do if you use DataDictionary in managed code only.