C#C
C#8mo ago
CoreDump

✅ Function argument class reference / clone (best practice(s))

Hello,

I'm a total newbie in C#. I mostly come from Rust and C/C++.

When writing a function what are the best practices to tell the caller (I'm mostly interested with a class (since they are reference types)):
  • The parameter will be taken (owned by the class from the called method)
  • You can use it after since the argument will be cloned (is it a good practice ? is ICloneable a good practice ?)
  • The argument will be modified after calling the method / function (is ref the standard ?)
Does it make sense to Clone() in C# to make sure a value lives on it's own ? Is it commonly used ?

I read the documentation (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters) and it clearly says about reference types (such as class):
The called method can't reassign the instance in the calling method. However, the called method can use the copy of the reference to access the instance members. If the called method changes an instance member, the calling method also sees those changes since it references the same instance.

How do you know in which case you are when calling a method / function ? (I hope my questions make sense, I apologize if it doesn't 🙏 -> I don't want to modify a value / variable and have unintended impact (same reference) on another variable)

Thank you very much in advance for any help
Parameter modifiers enable pass-by-reference semantics, with distinctions for read-only, and out parameters. The params modifier allows optional arguments.
Was this page helpful?