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

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

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

Will it be higher? Or?

+6
c #
source share
3 answers

As long as you are not in another thread, yes, the sample code is valid. A text field (or other elements of Windows forms) are still objects that can be passed and processed by methods.

+10
source share

Yes, that will work. You are not actually passing the object — you are passing the link to the object.

See "Parameter passing in C #" for more information on skipping compared to passing by value.

+8
source share

For any reference type, this is normal - you passed a reference to the object, but there is only one object, so the 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 (that is, they shouldn't have plausible properties).

If you need to do this with a structure, you can add "ref" - ie

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

All Articles