0

i basically want to define a templet data object , and use this templet data object to assign new data objects. then put different values to new data objects.

code like:

public class sData
{
    public  string name;
    public  int Number;
    public sData(string name,int Number)
    {
        this.poster_path = path;
        this.Number = Number;
    }
}

sData templet= new sData("aaaa","0");

sData realData1 = new sData();
realData1=templet;
realData1.Number=100;

but after realData1.Number=100;

i found the templet.Number is changed to 100

how can i just give the 100 to realData1 , but no the templet ?

Benny Ae
  • 1,897
  • 7
  • 25
  • 37

3 Answers3

2

Am I correct in saying that you'd like to setup some a factory object which will create data objects with pre-defined set of values (i.e. a template)?

The code you have above won't do that. You have only created one object but you have two different references to it.

Perhaps something like this will do what you need:

public class sData
{
    public string name;
    public int Number;
    public sData(string name,int Number)
    {
        this.poster_path = path; //copied from question, this might need updating.
        this.Number = Number;
    }

    sData CreateCopy()
    {
        return new sData(name, number);
    }

}


sData template = new sData("aaaa","0");

sData realData1 = template.CreateCopy();
realData1.Number=100;

This still doesn't feel very elegant, perhaps separate classes for the factory and the data object would be more appropriate, but it's hard to say without more context.

jaquesri
  • 188
  • 2
  • well i know that way, but the big class is generated by EF and no supposed to edit. so far i just get all the columns copy to each new object.... – Benny Ae Nov 21 '13 at 23:46
0

You are assigning the object variable of templet to realData1 and this way you are still referencing the same object in memory:

realData1=templet;

You can assign the values instead of the object itself:

realData1.name = templet.name;
realData1.Number = templet.Number;
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
0

Class is of reference type and the reference variables of class sData realData1 and templet point to the same memory location in heap, so the value of templet is getting overwritten by the value realData1.

par181
  • 401
  • 1
  • 11
  • 29