0

Let's say I have an object like so:

public class MyObject
{
    string MyString {get;set;}

    public MyObject DeepCopy()
    {
        return new MyObject { MyString = ??? } // string.copy(MyString), or MyString ?
    }
}

The goal is to cache this object (IMemoryCache). Is it safe to use MyString = MyString? Or will it's reference point to unallocated memory when the scope of MyObject will end?

I am wondering, as the string itself is immutable, so if the reference stays valid, it seems like a good idea to not copy each character (string.copy), which might be costly for nothing.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
David Gourde
  • 3,709
  • 2
  • 31
  • 65
  • 1
    There's no need to make a copy of the string as it is immutable. – Sean May 13 '20 at 14:15
  • 1
    [`String.Copy`](https://learn.microsoft.com/en-us/dotnet/api/system.string.copy?view=netcore-3.1#remarks) is obsolete already – Pavel Anikhouski May 13 '20 at 14:16
  • 1
    It's not entirely clear which question in your post you're meaning to ask. As far as whether the reference will remain valid, see first marked duplicate. It is fundamental to GC-based systems that references (except explicitly weak ones) will _always_ be valid. An object is only collected when it becomes unreachable; if you have a reference to it you can access, _it's not unreachable_. As far as whether copying the string reference is safe in cloning, of course it is. The object's state can never change, so there's never a reason to make a copy of it. Just use the original object. – Peter Duniho May 14 '20 at 00:18

0 Answers0