The Force function returns a value and makes a C # compilation error

I have a class and method in this class. However, this class method returns a string. When I call the class method, I do not receive an error message, even if I do not receive the return string value. Is there a way I can do C # and .net make me grab the value when returning the value. Here is an example of what I mean.

1- create a class test.

class test { public string mystring() { return "BLAH"; } } 

2- call a class method from a program or another class

 test mystring = new test(); mystring.mystring(); 

My compiler, while working in Visual Studio, does not complain that I am not collecting the return value. Is this normal or am I missing something. Can I get the compiler to notify me that the function is returning a value, but I am not catching it?

Thanks in advance for any suggestions you may have.

+6
source share
4 answers

You can convert this property instead of a method:

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

Then you cannot compile if you just call the property:

 myString.myString; //Results in "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" Error 
+7
source

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

It is generally accepted not to write return values. Examples in the main libraries (for example, adding elements to a Hashset<T> , the function actually returns a bool to indicate whether it was actually added or already existed - depending on the particular implementation, I may or may not care about that).

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

+1
source

You can try to enable warnings as errors by right-clicking the project in the solution explorer, clicking "Properties", go to the "Assembly" tab and set the Warning for all as errors for everyone. This will force you to resolve all warnings before you can create them, and it will capture some of you-not-assign-scripts.

The compiler cannot know that the only purpose of your method is to return a string or if it does some work that affects the state, and therefore it cannot complain when you are not assigning a result to something.

However, you can configure it as a receive property only for a MikeH response. This will complain if you don’t assign him anything.

+1
source

If your function has side effects, then you must create an unused variable and a catch value. The compiler, by release options, deletes this variable.

But if you don’t have any side effects in the function: you can use visual studio tools such as “View Window” and “Direct Window”

0
source

Source: https://habr.com/ru/post/1206589/


All Articles