Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By jmcilhinney

Thread: Parameters in functions

  1. #1
    VitzzViperzz is offline C# Forum Enthusiast
    .NET Framework
    .NET 4.5
    Join Date
    Jan 2017
    Posts
    36
    Rep Power
    6

    Parameters in functions

    Hello,

    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?

    Cheers

  2. #2
    jmcilhinney is offline C# Forum Moderator
    .NET Framework
    .NET 4.0
    Join Date
    Apr 2011
    Posts
    1,468
    Rep Power
    118
    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'.
    VitzzViperzz likes this.

  3. #3
    VitzzViperzz is offline C# Forum Enthusiast
    .NET Framework
    .NET 4.5
    Join Date
    Jan 2017
    Posts
    36
    Rep Power
    6
    A clear and well explained answer.

    Thank you.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •