1

I have a class like

public class ControlViewModel 
{ 
  public string FieldType { get; set; } 
  public string FieldName { get; set; } 
}

and i create object ans set value for above class in controller side like,

ControlViewModel cvm = new ControlViewModel(); 
cvm.FieldType ="TEXT"; 
cvm.FieldName ="TEXT1"; 

Now want to copy 'cvm' object to another object and change value 'FieldName' only

Ezhumalai
  • 163
  • 1
  • 2
  • 10
  • 1
    Possible duplicate of [Creating a copy of an object in C#](https://stackoverflow.com/questions/6569486/creating-a-copy-of-an-object-in-c-sharp) – Backs Dec 18 '17 at 04:28

1 Answers1

3

Using clonning of object

// Implement ICloneable to clone the object
public class ControlViewModel : ICloneable
{ 
  public string FieldType { get; set; } 
  public string FieldName { get; set; } 
  public object Clone()
    {
        return this.MemberwiseClone();
    }
}

ControlViewModel cvm = new ControlViewModel(); 
cvm.FieldType ="TEXT"; 
cvm.FieldName ="TEXT1";

// Copy object    
ControlViewModel cvm2 = (ControlViewModel)cvm.Clone() ;
cvm2.FieldName ="TEXT2";

MemberwiseClone() Creates a shallow copy of the current System.Object. ref https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

programtreasures
  • 4,250
  • 1
  • 10
  • 29