What is the best way of the following 2 suggestions to modify a property on an object that is being modified by a class that accepts the object as a parameter?
- Have the class work on the object and a return a value which you then assign to the object
or.
- Pass the object in using the ref keyword and have the class amend the object without actually returning anything.
For example, I have a Person object with a First Name and Last Name and 2 different ways to create the Full Name.
Which is the best way?
public static void Main()
{
Person a = new Person { FirstName = "John", LastName = "Smith" };
Person b = new Person { FirstName = "John", LastName = "Smith" };
NameProcesser np = new NameProcesser();
// Example A
a.FullName = np.CreateFullNameA(a);
// Example B
np.CreateFullNameB(ref b);
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
}
public class NameProcesser
{
public string CreateFullNameA(Person person)
{
return person.FirstName + " " + person.LastName;
}
public void CreateFullNameB(ref Person person)
{
person.FullName = person.FirstName + " " + person.LastName;
}
}