#272 – Differences Between ref and out Parameters

Ref and out parameters in C# are implemented in the same way, in the compiled code.  In both cases, a parameter is passed by reference, giving the method called a chance to change the underlying value.

ref and out parameters different purposes:

  • ref parameters are for input/output – a value is passed into a method and a new value is passed out
  • out parameters are for output – a value is passed out of a method

The compiler enforces the following rules:

  • ref parameters
    • A value must be assigned to parameter before method is called
    • Parameter may be referenced inside method before being written to
    • Parameter may be written to before returning from method
  • out parameters
    • A value may be assigned before method is called (but cannot be used inside method)
    • Parameter may not be referenced inside method before being written to
    • Parameter must be written to before returning from method
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: