Is it OK not to handle returned value of a C# method? What is good practice in this example?

后端 未结 10 2001
南方客
南方客 2020-12-07 23:49

Out of curiosity...what happens when we call a method that returns some value but we don\'t handle/use it? And we also expect that sometimes this returned value could be rea

相关标签:
10条回答
  • 2020-12-08 00:40

    It depends on the returned value it self.

    The compiler will generate that value in the caller method, So if the value is IDispolable or expose Close method or if it have resources that should be released, then you should not ignore it and dispose it properly, or else you may suffering from problems and memory leaks..

    For instance, if the returned value is a FileStream and you did not close the stream, the file may not closed until your application is terminated, more over if your application try to open the file again, it may throw exception that indicates "The file is in used by another process". So you should be careful on that kind of returned object and never ignore it!

    0 讨论(0)
  • 2020-12-08 00:43

    If your function do some changes to other objects (for exemple a DB), I think it's okay to not handle the returned object if you don't need it.

    0 讨论(0)
  • 2020-12-08 00:44

    From a memory management point of view thats fine - if the calling function doesn't use it, it goes out of scope and gets garbage collected.

    In this particular case DataTable does implement IDisposable so its not all 100% fine:

    If the returned object implements IDisposable then its a good idea to dispose it, for example:

    using (var retVal = InsertIntoDB(...))
    {
        // Could leave this empty if you wanted
    }
    
    0 讨论(0)
  • 2020-12-08 00:45

    I'm certain that this doesn't cause any problems, otherwise C# wouldn't be a very reliable language.

    I'm guessing the compiler isn't smart enough to optimize this. What most likely happens is the ordinary logic inside the function call is executed, e.g. creating the object and allocating memory for it. If a reference type is returned but not captured, garbage collection will free up the memory again.

    As others have stated, from a design view ignoring the return value does indicate a problem and most likely you should be looking at the return value.

    0 讨论(0)
提交回复
热议问题