I have two objects say Object1,Object2.
The two objects have the same properties.
My code is like below
Object1.property1=Object2.property1; // Object2.property1=**x**
Object2.property1= **y**;
When I try to retrieve the Object1.property1 it is displaying y.
Here I Don't want to change the Object1.property1 but it is Getting Modified when Object2.property1 has changed.
My Questions is
Why my code is behaving like that or Is there any concept that i don't know in c# ?
It is behaving like that because you don't actually have 2 objects. You only have one.
Object1 and Object2 are simply variables. They are not objects themselves. They store a "reference" that points to the object. You can use the variables to access the object. In some point in your code, you most probably have written
Object1 = Object2;
or
Object2 = Object1;
This makes the two variables hold 2 references that refers to the same object. When you edit the object by accessing through the variable Object1, you can see the effect by accessing the object through Object2. Because they are the same object.
Fore more details you read concept of : Deep Copy vs Shollow Copy
if you want to change that behavior than you need to make use of cloning/copy , right now you are assigning reference and that's why its changing in both the object ,
as property is byte array then you can do like this ,Array.CopyTo Method (Array, Int32)
Array1.CopyTo(Array2, 0);//
so in your case its like
Object2.property1.CopyTo(Object1.property1,0);
Object2.property1= **y**;
You might have to have a look at this Microsoft doc. The concept of value and reference types variables is a very basic and very important concept of c#.
Simply said: if you crate an object like this:
object2 = object1;
You dont really create a new object. You just reference the first object with the second one. If eiter of those gets edited both do at the same time since they are the same object after all.
Unfortunately there is no built in way to simply clone an object, but you coud create an overload to create a new object and pass the source object as argument tocopy all the attributes individually. if there are too many attributes you could also use reflection to procedurally copy all attributes defined in the object.
Related
I have read a bunch of code about C# object cloning.
For some reasons I wanted to use reflection to perform the cloning.
I have an object that contains a simple data (int, string, List<string>, List<int>, DateTime, double or other simple value types). The object is created by simple boxing.
object ob = 5;
Now using code like this DeepCloneHelper or this one fail all in the same way. Using this clone code on an object containing a primitive data they return the same object. The following sample code will return ob2 that is ReferenceEqual to ob1
object ob1 = 5;
object ob2 = DoSomeClone(ob1);
How to write a simple clone code for such types?
I searched a lot also here in SO, so I appologize if this question is a duplicate.
Explanation:
I have a common object that holds some data and references (origin of the data). The plain data itself (datatype see above) is saved in an object. For the primitive types it is just the boxed value.
In some cases I need a copy of the outer class, because I want to give this function to a simulation that might change the data. The object itself is cloned via a constructor. Now I need a copy of the data too. Using any cloning function would create a copy not a clone of the values.
The answer was given in the comments: Primitive types are immutable when boxed and so there is no need for cloning!
So storing a new value (i.e. int) in it will create a new object!
I'm having strange issue where I am creating a new object which contains a parameter for another object (paramObj) I use through my function. So, paramObj is used in an object constructor, but it ends up being altered after the constructor is called. Since C# is pass by value, I'm not sure why this is happening.
My code:
void MyFunction(List<string> filesets)
{
foreach(Fileset fs in filesets)
{
//At this point, fs.allFiles.Count is 30. The MyNewObject class
//takes a Fileset as a parameters and eventually clears the
//Fileset.allFiles List, making the count 0.
MyNewObject tmpObj = new MyNewObject(fs, null, "default");
//At this point, fs.allFiles.Count is 0, but I expect it to be 30
}
}
The MyNewObject class simply clears the allFiles list contained within a Fileset class. Why is that showing up after the constructor if C# is pass by value?
You´re right in that everything in .NET is passed by value. Even references - and this is what fs actually is - are passed by value. Thus, when you pass fs around your method will have a copy of that reference. This reference however references the exact same object, making any change on that reference modifiying the backing object also.
So in your constructor you have a second reference to the FileSet-instance referenced by fs.
This more or less leads to the conclusion, that objects are effectivly passed by reference.
There´s no simple way to circumvent this. It depends on why you even modify anything on that object within the constructor at all. You could try to copy the provided object referenced by fs within your constructor, e.g. by implementing IClonable within FileSet or by providing a copy-constructor within that class or whatever. However depending on what FileSet and it´s members are you will need some deep copy of the provided instance.
For further reading on how to make a deep copy of an object look here: Deep cloning objects
Normally, all the objects are passed by reference as parameter to the method. On the other hand most of the primitive data types such as integer, double, Boolean etc. are passed by value.
I have an AnonymousType object that contacts two fields with their values. How can I access the value of these fields?
Ex:
SourceTypeObject { Source_Type_Id = 1, Source_Type_Name = "bibliography" }
I need to do something like : SourceTypeObject.Source_Type_Id
Is that possible?
EDIT:
Here's what I get if I tried to access the property directly:
Yes, this is the exact purpose of anonymous types. The only thing that might prevent you from doing so is if you passed the anonymous type around as a parameter with type "object". This would hide information about the anonymous type, and it would look like just any old object then.
The only recourse if this is the case is to use reflection, which is slow and awkward. Anonymous types are a meant to be a very "local" phenomenon, and if you find yourself wanting to use them elsewhere in the program, it's worth the time to promote it to a real type.
EDIT: In response to the image you posted, assuming the array is declared locally just outside of view, try to replace the object SourceTypeObject with var SourceTypeObject. This allows it to infer the anonymous type instead of being told that it's an object.
using reflection in c# I need to get only reference to object, not copy, is it possible?
object data = actualData.GetType().GetProperty(properties[0]).GetValue(actualData, null);
variable data should be only reference - if I change something inside, I would like to perform the same changes in actualData variable, but it seems to copy value from actual data and any change stay only in data variable. Any suggestion?
Thanks!
It seems that your property is of value type. Or maybe it is of reference type but it creates a new instance of resulting class instead of reusing it.
If this is a case, then I'm afraid this can't be done in general - properties are methods, so the result value of property is calculated, you cannot observe when that result would be changed.
But if you can change class of which actualData is the instance, then you can implement INotifyPropertyChanged interface and subscribe to its event PropertyChanged in your code.
If this is not possible then you can remember the result of ...GetProperty(), but you have to call GetValue() on it each time when you need the data.
While debugging an ASP.NET application, I want to get a print-out of the entire state of a very large object. I want all the properties and values in that object and the same for every object-property, recursively.
Because the front-end of the application times out after a significant delay, I can't add a watch or use the Immediate window or hover over the object, since there won't be adequite time to fully examine the object.
Is there a way of getting a complete printout of an object in debug mode, or say, a utility or a C# function that would do this?
You could use reflection to get the list of all properties and fields on the class type, then use that to get the runtime values of each of those properties / values and spit them to the console.
The PropertyInfo type (here) and FieldInfo type (here) are what you need to get from the Type object for your own class instance.
MyObject myObject = ... //setup my object
Type myType = myObject.GetType(); //or Type.GetType(myObject); //I think
PropertyInfo[] properties = myType.GetProperties();
FieldInfo[] fields = myType.GetFields();
properties[0].GetValue(myObject); //returns the value as an Object, so you may need to cast it afterwards.
Reflection really is your best bet here. You can start with your root object, get all of its properties and their values, and if necessary get the properties and values off of those values recursively. It's a really powerful technique, and if you don't know it yet you probably should learn it anyway, and this makes a perfect project to learn with. :)