Mitt Rodenbaugh
Mitt Rodenbaugh

Reputation:

C#: How do you pass an object in a function parameter?

C#: How do you pass an object in a function parameter?

public void MyFunction(TextBox txtField)
{
  txtField.Text = "Hi.";
}

Would the above be valid? Or?

Upvotes: 6

Views: 11987

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1064114

For any reference-type, that is fine - you have passed the reference to the object, but there is only one object, so changes are visible to the caller.

The main time that won't work is for "structs" (value-types) - but they really shouldn't be mutable anyway (i.e. they shouldn't really have editable properties).

If you needed to do this with a struct, you could add "ref" - i.e.

public void MyFunction(ref MyMutableStruct whatever)
{
  whatever.Value = "Hi."; // but avoid mutable structs in the first place!
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503539

Yup, that will work. You're not actually passing an object - you're passing in a reference to the object.

See "Parameter passing in C#" for details when it comes to pass-by-ref vs pass-by-value.

Upvotes: 8

Timothy Carter
Timothy Carter

Reputation: 15785

So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods.

Upvotes: 10

Related Questions