❔ ✅ Need help with methods and parameters
I'm stuck on the return methods, specifically how to use the ref and out keywords.
Any sites or videos that discuss these topics in the console class?
9 Replies
If you're a beginner to the language then you really don't have to worry about ref and out
or at least ref
Well I guess that I'm not a beginner anymore. We covered those topics in my class and I just can't grasp how to use it
Have you ever used
int.TryParse
?ref
$refvsvalue
out
-> the method u call will set it to a value, an earlier value would be overwritten, the variable can also be uninitialized.
Example1
and Example2
do exactly the same, the difference is simply that the variable declaration is "inlined", so u save one line of code to write, but thats it
most common are the TryPase
methods, as Thinker already mentioned.
eg this to get an int number:
ref
is similar to out
, the main difference is that the called method doesnt have to set it to a value
(its basically like a pointer in other languages)
to explain why these are needed goes into how parameters are passed. and there are 2 types of paramaters to think about, value types and reference types.
value types are simple values like 5
, 'a'
, -1.324
when calling a method, the value will be copied, and this copy is used in the method
it prints 5
for the reason, that when calling MultiplyByTwo(someNumber)
, the method has its own copy of the value.
that copy will be modified in MultiplyByTwo()
, but it does not affect someNumber
at all
in the previous examples using out
/ref
its a bit different. basically the memory of the variable is passed to the method, and the value at that address is modified
this brings us to reference types:
references are pointing to some memory by default basically simply containing the memory address
in both methods that reference is copied and passed to the respective method.
in MultiplyByTwo1
that copy still points to the same memory and that memory is modified, so it really changes someNumbers
in MultiplyByTwo2
a new memory block is created, the content written and then numbers
(a reference to some memory) is replaced.
but because this is just a copy of the reference, it doesnt affect someNumbers
at all
for that to happen u would have to use ref
, so that a reference to the reference of the memory block is passed
@Alex se Chipotle is ⤴️ understandable, or do u have questions?Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.Thx. This helped
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.