简体   繁体   中英

C# language theory question

Given the following method,where I pass configuration byref, then loop through it using a foreach named collection. In the following code sample, will the values that I change in the loop be updated in the main object I passed through by ref, what I mean is NO shallow copies? Or can you spot any mistake I've made.

More specifically the line where I call config.Value = ..... the configuration object has a collection of configurations, so will these be updated in the main object (configuration) after this function is called?

Thanks in advance.

public static void DecryptProviderValues(ref MyConfiguration configuration)
    {
        foreach (var provider in configuration.Providers)
        {
            var configItems = provider.Configurations;
            foreach (Configuration config in configItems)
            {
                if(EncryptionManager.IsEncrypted(config.value))
                {
                    config.Value = EncryptionManager.Decrypt(config.Value);

                }
            }
        }
    }

Assuming that all the items here are classes (not structs), then yes, but actually there is no need for configuration to be passed as ref ; you are already passing a reference (by value), and you aren't re-assigning the reference, so no need for ref here at all . Your changes are preserved and available to the caller.

For exactly the same reason that this would work:

Configuration x = new Configuration();
Configuration y = x;
x.Value = "abc";
Console.WriteLine(y.Value); // writes "abc"

here, because Configuration is (presumably) a class , there is only one object, and two variables that refer to the same object (at a simplified level, they are glorified pointers to the same object).

There is no need to pass configuration by ref in your case, since in C# you're manipulating references to instances of classes already.

You would use ref to pass value types like int or struct by reference.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM