This is probably a simple question. Suppose I have a object called Users and it contains a lot of protected variables.
Inside that Users class I have a method that creates a temporary Users object, does something with it, and if successful, transfers all the variables from the temp Users object into the one I have.
Is there some fast way to transfer all the variables from one Users object into another Users object without doing this using C#?
this.FirstName = temp.FirstName;
this.LastName = temp.LastName;
........75 variables later......
this.FavoriteColor = temp.FavoriteColor
-
A better approach is to implement the IClonable interface. But you'll find it doesn't save you a lot of work.
-
You should check out cloning in C#.
http://stackoverflow.com/questions/78536/cloning-objects-in-c
-
A better solution might be to move whatever this method is outside of your class, and then just assign the temp user object to your main user object reference like so:
_User = tmpUser;
sparing you the 75 lines of code. Whenever I have a class creating an instance of itself inside one of its own methods, I always like to blink a couple of times and make sure I really need to be doing that.
danmine : I didn't know it was bad practice. How about if I call a DataReader with a GetValue()?Jon Skeet : @MusiGenesis: Factory methods are pretty standard though, and have many advantages over public constructors.MusiGenesis : @Jon: does that sound like what's going on here?MusiGenesis : @Danmine: can you post more of your method? I'd be interested in knowing what you're trying to do there. -
I think serializing and then deserializing an object will create a new object instance. This should be identical to the former object.
0 comments:
Post a Comment