Using ref for large data types.
Hi, just looking for a little clarification on the ref keyword when passing data into a function.
I've hot an API endpoint which takes in files which passes them though to a function which checks them and sorts them into an appropriate destination directory.
I've got a function in another class which checks the data type is supported, among other things. Would I be right to pass the incoming multipart File data to it using a ref value to avoid making a copy of it? Some of the files can run up to 200mb in size.
Thanks for any help.
6 Replies
If you pass in your
File
class, whatever it's called or contains, you pass the reference to it not a copy. So no need to use ref
here.Hi thanks for the reply. What about if I was to pass a list containing incoming data as I am here in my GET endpoint?
In the following function I've got
Would it be correct to put ref in front of when calling the function or will that do a copy?
There may be some intricacies which I've forgotten around the reference pointer on reference types using the
ref
keyword but the object is still the same object
ASFAIK a list just contains a copy of the reference not the actual object. Meaning if you change something something on an object inside SaveDataToStorage
you'll see the same changes when you step outside in files
. You can confirm this quite easily
I would not. Confirm that by making a change to one of the files in the list inside CheckValidFileTypes
and step outside back into the SaveDataToStorage
method, and the change is still reflected. You'll know then that no copies are made and it just passes around references
Short answer: use-case for ref
is actually quite limitedRight! Thanks for your help with a succinct answer and explanation. I was getting sick of trying to decipher the correct approach from StackOverflow :blobthumbsup:
No worries, good luck 🙂
unless the types you're passing in are structs they're already passed as a reference instead of a copy