Force function to return value and make compile error C#

后端 未结 4 1040
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-18 06:23

I have a class and a method within that class. However this class method returns a string. When I call the class method I don\'t get an error even though I\'m not catching

相关标签:
4条回答
  • 2021-01-18 06:36

    In a word, no. Not by force as such.

    It's commonplace to not capture return values. Examples in the core libs abound (adding elements to a Hashset<T> for example, the function actually returns a bool to flag whether it was actually added or if it already existed - depending on individual implementation I may or may not care about that).

    Of course, you can always just do something like string str = MyFunction() each time then never use str but I guess you probably already knew that.

    0 讨论(0)
  • 2021-01-18 06:39

    If your function has side effects then your should create unused variable and catch value. Compiler on release options delete this variable.

    But if you don't have side effects in function: you may use visual studio tools such as "Watch window" and "Immediate window"

    0 讨论(0)
  • 2021-01-18 06:54

    You could convert this to a property instead of a method:

      public string myString
      {
        get
        {
          return "Blah";
        }
      }
    

    Then you can't compile if you simply call the property:

    myString.myString; //Results in "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" Error
    
    0 讨论(0)
  • 2021-01-18 06:57

    You can try turning on warnings as errors by right-clicking the project in solution explorer, clicking Properties, going to the Build tab and setting Treat warnings as errors to all. This will force you to resolve all warnings before you can build and will capture some of the you-didn't-assign-this scenarios.

    The compiler can't know that the only purpose of your method is to return the string or if it does some work that affects state, and so it can't complain when you don't assign the result to anything.

    You can, however, set it up as a get only property per MikeH's answer. This will complain when you don't assign it to anything.

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