tags:

views:

81

answers:

1

Say I have

public class family
{
   public person father;
   public person mother;
   public person[] child;
}

public class person
{
   public string name;
   public int age;
}

What I want to do is add a function to family that will allow me to specify the location I want a new person saved to.

If there were C I would pass in a pointer to person so I could point it at a new person but I am somewhat new to C# and don't know what to do here. So I want it to look something like this:

public void SavePerson(int newAge, string newName, ??? location)
{
   person addMe = new person();
   addMe.age = newAge;
   addMe.name = newName;
   location = addMe;
}

I don't want to change the previous content of location. If it used to point at Frank, I want to keep Frank just the way he was, I just want it to now point at John (because other things may still be pointing at Frank)

The reason I need this is because I have an interface and classes much more complicated than this. But there is one class I need to create and save a lot (and it appears all over in a large NHibernate created object) and I would like to roll that into one function for simplicity's sake.

+4  A: 

The idiomatic C# way of doing things would be to simply return the new object:

public Person CreatePerson(int age, string name)
{
    Person person = new Person();
    person.Age = age;
    person.Name = name;
    return person;
}

Usage:

family.Children[0] = CreatePerson(11, "Frank");
family.Children[1] = CreatePerson(15, "John");

Alternatively, you can pass the Person[] and an index to the method:

public void SavePerson(int age, string name, Person[] persons, int index)
{
    persons[index] = new Person();
    persons[index].Age = age;
    persons[index].Name = name;
}

Usage:

SavePerson(11, "Frank", family.Children, 0);
SavePerson(15, "John",  family.Children, 1);

But I'm not sure why you'd want to delegate this responsibility to your factory method.


If you really want to manipulate variable contents by reference, you can do that using the ref or out keyword:

public void SavePerson(int age, string name, out Person person)
{
    person = new Person();
    person.Age = age;
    person.Name = name;
}

Usage:

SavePerson(11, "Frank", out family.Children[0]);
SavePerson(15, "John",  out family.Children[1]);

See: Parameter passing in C#

See: When is using the C# ref keyword ever a good idea?


But why not simply use object and collection initializers?

Person mom = new Person { Age = 41, Name = "Martha" };
Person dad = new Person { Age = 43, Name = "Dan"    };

Family family = new Family(mom, dad)
{
    new Person { Age = 11, Name = "Frank" },
    new Person { Age = 15, Name = "John"  },
};

See: Object and Collection Initializers

dtb
The Ref and Out keyword are what I was looking for but the object initializers may be what I go with here. Thanks!
Justin