简体   繁体   中英

C# - Using nullable types as parameters

Can anyone tell me if it is a good idea to accept nullable parameters for a function and then setting the parameter to null after using it? Would this be a good programming practice to free up unused resources? Ex:

public static bool SendEmail(MailAddressCollection? To, string Subject, string Body)
{
    // use the values stored in To, Subject, and Body to send the message.
    To = null;
}

No , it's not a good idea. What you're doing has no practical impact. The only variable you're setting to null is a local one for the method. That variable will go out of scope automatically anyway.

On the contrary, if you got that object as an argument, it means that there's a reference to that object outside of the current method anyway and you're not affecting that reference. So you're not helping the GC at all by doing anything inside the method as it is. The only way to have any non-local effect in this regard would be to pass all your arguments as ref and thus be able to set the passed variables to null. However, this would be absolutely horrible because every innocent looking method call could potentially ruin references that are assumed not-null later on.

Generally, what you should do in most applications is not think about it. The GC is a lot better at detecting the unused memory, because it can examine the stack for references and it has access to relevant metadata emitted by the JIT compiler that you don't get to see.

No, it's not. You've got a GC to take care of that for you. You're not in an unmanaged language, you don't need to dispose resources (unless they're IDisposable , of course).

No, this is a bad practice in managed environment such as .NET. Garbage collector in .NET can automatically collect objects with no references and free memory from them.

But there are rare exceptions. You can manually set reference to null and explicitly call GC:

public static void ForceGC(ref object obj) {        
    obj = null;
    GC.Collect();
}

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