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

后端 未结 10 2092
南方客
南方客 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:28

    All this talk about whether it is okay to ignore returned types is not needed, we do it all the time anyway in C#. Lots of functions you use as if they are returning void are not returning void. Think about a common function like Button1.Focus()

    Did you know that the .Focus() function returns a bool value? It returns true if it succeeded in focusing on the control. So you could test it as a bool by saying:

    if (Button1.Focus == true) MessageBox.Show("Button Focused successfully."); else MessageBox.Show("Could not focus on the button, sorry.");

    But normally, you don't do this. You just say: Button1.Focus();

    and you're done. I could give a hundred other examples where we ignore return values, like when a function runs but also returns a reference to something it created, but you don't care about the reference, you just wanted it to do the action (or you just want to simply check whether there is a reference or if it is null)

    The point is, we ignore return values all the time, even if you don't know it.

提交回复
热议问题