LogFAQs > #910119180

LurkerFAQs, Active DB, DB1, DB2, DB3, Database 4 ( 07.23.2018-12.31.2018 ), DB5, DB6, DB7, DB8, DB9, DB10, DB11, DB12, Clear
Topic List
Page List: 1
TopicCool function I wrote
Sahuagin
10/07/18 1:51:05 PM
#24:


Yellow posted...
The usefulness of our ref and in are lost on me currently. I will copy and paste this topic into a text file and read it before this topic purges. Although, Sahuagin you're using ref in the one case where you need to, since strings automatically copy themselves when passed, I noticed that.

ref in the ValidateAndClean method allows me to get a different string back than the one I passed in. I use it for validating phone numbers and things like that. so maybe the user typed a super messy string "1 11 - 4 3 2 1 ". I scan it just for numeric digits and make sure there are 7 of them, and then return the cleaned string which includes a hyphen "111-4321". using the ref parameter, your external variable can be modified by the function, allowing you to get back a different string.

var phoneNumber = PhoneNumberBox.Text; // "1 11 - 4 3 2 1 "
ValidateAndClean(ref phoneNumber); "111-4321"

not sure if you know this already but it's worth explaining. in C# there are value types and reference types. when you say int x = 5;, since int is a value type, you are creating an int sized space of memory and placing an int sized 5 value into that memory.

but strings and objects aren't value types they are reference types. when you say string str = "this is a string"; you are allocating a <string length> chunk of memory off to the side, storing the string in it, but then for the variable you are allocating a memory address sized space of memory (32 or 64 bits), and storing the memory address of the chunk of memory where the string lives into the variable. when you pass a string as a parameter, you are passing the memory address by value. when you use a ref string parameter, you are saying that a value might come up out of the function back into my variable and overwrite the memory address in my string variable with a different memory address (that points at a different string than before).

the same is true for objects. so a ref List<T> parameter means that you can get back a different List<T> memory address than the one you passed in, allowing the function to overwrite the memory address you have on the outside, changing the List<T> that you're working on to a different one. (the old list still exists in memory, you just lose that one reference you had to it. once all references to an object are gone, it is free to be cleaned up by the garbage collector.)

(also a technical thing with strings is that there is "string interning". so if you say string str1 = "asdf"; string str2 = "asdf";, the space for "asdf" is only created once rather than duplicating the space, and both variables hold the same memory address.)
---
... Copied to Clipboard!
Topic List
Page List: 1