Pass value in c #

How to pass an object "MyClass" (C #) by parameter by value method? Example:

MyClass obj = new MyClass(); MyClass.DontModify(obj); //Only use it! Console.Writeline(obj.SomeIntProperty); 

...

 public static void DontModify(MyClass a) { a.SomeIntProperty+= 100;// Do something more meaningful here return; } 
+6
source share
5 answers

By default, object types are passed by value to C #. But when you pass the object reference method to the method, changes to the object are saved. If you want your object to be incompatible, you need to clone it.

To do this, run the ICloneable interface in your class. Here is an example using ICloneable:

 public class MyClass : ICloneable { private int myValue; public MyClass(int val) { myValue = val; } public void object Clone() { return new MyClass(myValue); } } 
+9
source

By default, it is passed by value. However, you pass the reference to the object by value, which means that you can still edit the values โ€‹โ€‹inside the object.

To prevent the possibility of modifying an object in general, you will need to actually clone the object before passing it to your method. This will require you to implement some method of creating a new instance, which is a copy of the original object, and then transferring to the copy.

+4
source
 public static void DontModify(MyClass a) { MyClass clone = (MyClass)a.Clone(); clone.SomeIntProperty+= 100;// Do something more meaningful here return; } 
+2
source

You can create a Clone method for your object to pass the return value to your method. C # cannot pass reference types by value, so this can be a good alternative.

 public MyClass CreateClone() { return new MyClass() { SomeIntProperty = this.SomeIntProperty }; } 
+1
source
 class Program { static void Main(string[] args) { Person p1 = new Person() { Name = "Alsafoo", Address = new Address() { City = "Chicago" } }; Person p2 = new Person(p1.Address); p2 = p1.GetClone(CloningFlags.Shallow); p2.Name = "Ahmed"; p2.Address = new Address(){City = "Las Vegas"}; Console.WriteLine("p1 first name: {1} --- p1 city: {2} {0}p2 first name: {3} ---- p2 city: {4}", Environment.NewLine, p1.Name, p1.Address.City, p2.Name, p2.Address.City); Console.ReadKey(); } } public class Person { public Person() {} public Person(Address a) { Address = a; } public string Name { get; set; } public Address Address { get; set; } } public class Address { public string City { get; set; } } 

Download this extension https://www.nuget.org/packages/CloneExtensions/1.2.0

+1
source

Source: https://habr.com/ru/post/918678/


All Articles