Tuesday, April 10, 2007

Parameter Scope in C#

By scope, here, I mean 'value' type or 'reference' type.

The parameters are passed almost as in VB.net, by default a parameter is passed as 'value' type (ByVal in VB.net). In C# we don't use any specifier to indicate a 'value' type parameter.

For reference types we have specifiers 'ref' and 'out' with a subtle difference between both, which is, all 'ref' parameters must be initialized before being passed as an argument while 'out' parameters need not, whereas, all 'out' parameters must be assigned a value before the method ends. Properties cannot be passed as reference type parameters.

A method can be overloaded by chaging parameter type from value to reference and vice versa. (note that a change by 'ref' to 'out' or vice versa will not overload a method)

For more on this and sample code check this on MSDN online.

No comments: