So, I'm researching Structs vs Classes. So far I know the following:
Classes can modify the data within directly when passed to another function. Classes use more memory than a Struct.
Structs can be passed to a function, but the data is cloned within the function and not modifying the original data.
So, if I use a class, I can pass the data to a function and modify the data within the class directly from the new function.
If I use a struct, I can pass the data to a function, which makes a copy of the data to be used in the function, but doesn't affect the original data.
However, if I pass a Struct to a function with the Ref keyword, It then modifies the original data within the Struct.
With that in mind, what is the key difference between using a Struct with the Ref keyword, or just using a Class? Is it purely memory related? I've been using Structs, but I need to modify the original data - trying to work out if it's better to pass the Struct with the Ref keyword, or change all my Structs to Classes.
This is a very confusing question. Here are some guidelines that should help you make the decision:
what is the key difference between using a Struct with the Ref keyword, or just using a Class?
That is the wrong way to look at the difference between structs and classes. If you are passing a struct by ref in order to modify its fields, you are probably doing something wrong. Fields should be private, and structs should be immutable.
The key difference between using any ref argument and passing an object by reference is that the former is an alias of a variable , and the latter is a reference to an object . I regret that ref
was the C# design team's choice for syntax for the feature, as it is confusing. You should not think of it as passing a reference. You should think of it as aliasing a variable . That behind the scenes it passes a managed pointer to the variable is an implementation detail. The aliasing behaviour is the semantic meaning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.