Alex Rivera | Logout

Do you prefer to return the modified object or not?

Asked 2009-06-03T05:01:09.660
10
Class c = new Class( { Prop = "Initial" } );

I have the class above. How would you create a method to modify it?

public Class ModifyIt(Class c)
{
    c.Prop = "changed";
    return c;
}

or

public void ModifyIt(Class c)
{
    c.Prop = "changed";
}

Then called like this...

Class c = ModifyIt(c);
Console.WriteLine(c.Prop);
// changed

or this

ModifyIt(c)
Console.WriteLine(c.Prop);
// changed

Whats your preference?

Edit
Report

1 Answer

0

Actually I prefer the second style as the method is a mutator, hence, a new value is not expected to be returned, instead the actual value is expected to be modified. However you might need to indicate that ModifyIt accepts a ref variable just to indicate that the actual c will be modified. c here is passed by value, though it's a reference type, there's still a difference between passing reference types by value and passing reference types by ref. See the following:

public void ModifyIt(Myclass c) { c = new MyClass(); } 

in the above case the c variable will be passed by value (i.e. a copy from the reference will be passed and modified to point to a newly instanitiated object, which in turn means that you will have two objects of type MyClass in this case. Here's an example to illustrate:

Myclass s = new MyClass () { prop = "value" }; ModifyIt(s); Console.WriteLine(s.prob); // this will print "value"

though MOdifyIT instanitaited the referenct to a new object which should mean that prob will be initialized to null, it actually didn't instantiate s, it instantiated a copy of s. unlike the case if s was passed by ref.
Hope this helps!

answered 2009-06-03T05:15:57.067

Your Answer