0

I completely understand the use of out and ref in C# however why would I ever use out instead of ref as out is simply the same as ref just with restricted abilities. I see when it can be used but I don't see any point in ever using it really.

Thanks so much!

jer_francis
  • 153
  • 1
  • 11
  • 1
    In what situation? The answer will change depending on what you are trying to do. – gunr2171 Jun 16 '14 at 15:44
  • Look at `TryParse` group of methods, they all take `out` parameter. – Habib Jun 16 '14 at 15:44
  • 1
    The [out] keyword requires the method to assign its value. If you pass an uninitialized variable to a method that takes a ref then it will be a compile error 'use of unassigned local variable'. The TryParse and TryGetValue methods therefore use [out] – Alan Jun 16 '14 at 15:52
  • @Alan I think that answers my question, before I did not see the purpose in its existence. Thanks so much! :) – jer_francis Jun 16 '14 at 16:04
  • Think of it like an indication to another developer about what you're going to do with the value he provides: `ref` => You can given me a variable assigned to some value, I might use it, I might replace it with something else, your variable might point to something else than what you set it to when I'm done with it. `out` -> You can give me a variable that is or is not assigned to something; it doesn't really matter because I absolutely definitely will change it to point to something else by the time I'm done and hand control back to you. Expect the value you gave me to be GONE – Caius Jard Aug 14 '19 at 13:54

0 Answers0