Parameters in functions


Well-known member
Jan 16, 2017
United Kingdom
Programming Experience

I am reading a book on C# and we are covering functions in C#. The book is also covering how References and Out are used in C# to pass arguments. But I am slightly baffled.

I started to understand parameters in functions and how they are used until I got to Out parameters.

This is where I started to scratch my head a little. My first question is why are they used? I looked at MSDN but the explanation was way too complicated. The only bit I understood was the fact that they signify a reference parameter.

Could someone give a simple explanation as to what they do and why they are useful?

A C# function can only return one object. That object can be as complex as you like but it can only be one object. If you want to get more than one object out of a function then you could create a type specifically for that purpose, i.e. define a class with one property for each of the objects that you want to get out, but that is rather kludgy. "By reference" parameters exist in order to allow you to get additional objects out of a function without having to define new types specifically for the purpose.

The short explanation is that parameters with no qualifier are used to pass data into a method only, parameters with an 'out' qualifier are used to pass data out of a method only and parameters with a 'ref' qualifier are used to pass data both into and out of a method. A common example of the use of an 'out' parameter is in TryParse methods, e.g. Double.TryParse. That method is used to try to parse a String to a Double. The function returns a Boolean that indicates whether the attempt succeeded or not and, if it did succeed, the numeric value produced is retrieved via an 'out' parameter. In that case, the parameter does not need to get data into the method but it does need to get data out, so 'out' is used rather then 'ref'.
Top Bottom