C
C#2y ago
Moods

with or without ref

so i learned that in c#(or most oop languages) when you create a method that takes an object as a parameter, and you call said method and pass an object of the same type as an argument, it passes the reference to the caller. so if you were to alter any properties of the object parameter in the method, it affects the object that was used as a parameter something like
void ChangeName(Person p) {
p.Name = "Alice";
}

Person person = new Person();
person.Name = "Bob";
ChangeName(person);
void ChangeName(Person p) {
p.Name = "Alice";
}

Person person = new Person();
person.Name = "Bob";
ChangeName(person);
i assume that after the last statement person's Name property is now "Alice". i was reading up the docs and it mentioned you would use ref before an object parameter if you wanted to alter the original object argument and I'm confused cus isnt this how objects already worked like..?
6 Replies
x0rld 👻 🎃
you pass the reference of that object ref would be for a valuetype I think 🤔
Moods
MoodsOP2y ago
yeahhh i know how it works for value types but the docs covered reference types too and i got all confused ok reading it again i believe i understand it now. with ref it's possible to make the original object point to a new memory
Aaron
Aaron2y ago
ref allows you to reassign, when talking about reference types
Moods
MoodsOP2y ago
yep
Aaron
Aaron2y ago
dunno why I said out
MODiX
MODiX2y ago
Windows10CE#8553
REPL Result: Success
void Assign(ref string s) => s = "abc";

string s = null;
Assign(ref s);
s
void Assign(ref string s) => s = "abc";

string s = null;
Assign(ref s);
s
Result: string
abc
abc
Compile: 458.034ms | Execution: 36.602ms | React with ❌ to remove this embed.
Want results from more Discord servers?
Add your server