Reputation: 47743
Is there a way that I can pass in a reference to an object, manipulate it inside my method which directly changes the referenced object?
For instance I want to pass a dropdownlist into my method, manipulate it and be done. This method is going to take in any dropdownlist:
public static void MyMethod(Dropdownlist list1, ref DropdownList list2)
{
// just manipulate the dropdown here... no need to returnit. Just Add or remove some values from the list2
}
obviously I can't just pass a dropdownlist object to list2. So how can I do this? I am going to remove some values in the list. And this will be a nice utility method so I don't have to repeat this code all over the place for this functionality that I'm going to be performing in the method.
Upvotes: 1
Views: 717
Reputation: 754725
If you are manipulating the internal data on a single reference type then you don't need anything special on the method signature. When passing an object which is a reference type to a method you do not pass a copy. Instead you pass a reference to the object. Manipulating this reference will change the original object.
void MyMethod(List<string> list) {
list.Add("foo");
}
void Example() {
List<string> l = new List<sting>();
MyMethod(l);
Console.WriteLine(l.Count); // Prints 1
MyMethod(l);
Console.WriteLine(l.Count); // Prints 2
}
Now if you want to change where the original reference points to, you'll need a ref modifier.
Upvotes: 2
Reputation: 269368
DropDownList
is a reference type, so you should just be able to pass an instance into your method and manipulate it. (The object referenced inside your method is the original instance.)
You don't even need to specify the ref
modifier so long as you're only updating the existing object, rather than replacing it.
Upvotes: 2