I have a method, which returns void. It sets some values in an array, depending on an if/else statement.
However, if the code enters the else statement, this operation cannot be performed. What could I return to the calling method (a method in the code-behind of a winforms form), to indicate this operation did not suceed?
Thanks
You could change the void to int, bool or a result enumeration of some sort. The caller can then retrieve this value and check if the call was successful. For example, true is returned if the operation succeeded and false is returned if it didn't. If the method has to remain a void, you could use an out parameter which the caller then reads to check whether or not the call was successful. Alternatively, you could throw an exception and have the caller handle it.
you can use as OUT parameter, Out parameter must be assigned within the method, before it return the value or else compiler will raise the error.
void SomeFunction (someparameter of yor req, out bool result)
{
if(success) // if everty things go well, you assign out variable
{
result=true;
}
else
{
result=false;
}
}
Out Parameter Documentation
Have your method return a bool indicating success/failure.
Related
I have a loop inside a C# method that has the following structure.
do
{
getUserInput();
if (inputIsBad)
{
doSomethingElse();
}
} while (inputIsBad);
alternately, with a while loop:
getUserInput();
while (inputIsBad)
{
doSomethingElse();
getUserInput();
}
But both methods use redundant code: the do-while has both an if statement and while loop checking the same condition; the while loop calls getUserInput() both before and inside the loop.
Is there a simple, non-redundant, non-ad hoc way to do what these method patterns do, either generally or in C# specifically, that only involves writing each basic component once?
Assuming that getUserInput(..) can be converted into a expression yielding a boolean value*..
while (getUserInput()
&& isBadInput()) {
doSomethingElse();
}
// Prompts for user input, returns false on a user-abort (^C)
private bool getUserInput() { .. }
Other variations (presumed without non-local state) shown in comments.
*Trivially, it can always be written as a wrapping function - see Local Functions, introduced in C#7. (There are other methods for the same effect, some of which I consider 'too clever'.)
// local function
bool getUserInputAlwaysTrue() {
getUserInput(); // assume void return
return true;
}
while (getUserInputAlwaysTrue()
&& isBadInput()) {
doSomethingElse();
}
This can be followed to pushing out the logic further, in some cases. The general premise holds: getUserInput() is always invoked prior to the next isBadInput().
// local function or member method
// Prompt for user input, returning true on bad input.
bool getCheckedUserInput() {
getUserInput(); // assume void return
return isBadInput();
}
while (getCheckedUserInput()) {
doSomethingElse();
}
do
{
getUserInput();
if (!inputIsBad) break;
doSomethingElse();
} while (true);
I would use a boolean variable, which you need to declare outside the body of the loop. That way you only need to run the inputIsBad check once. I have turned it into a method as well, since that seems more logical.
bool badInput = true; // Assume bad until checked -- failsafe.
do
{
getUserInput();
badInput = inputIsBad();
if (badInput)
{
doSomethingElse();
}
} while (badInput);
Building on user2864740's answer:
Assume getUserInput() can be converted into a function which returns true if the input is good and bad otherwise. Assuming its original return type wasn't boolean or void, return its original return value via an out or ref parameter depending on the case, e.g.
int originalReturnValue;
while (!getUserInput(out originalReturnValue))
{
doSomethingElse();
}
...
bool getUserInput<T>(out T output)
{
// method body
}
I am writing an HTTP wrapper class object in C# and I would like to give the main method the ability to receive a function as a parameter and then execute it on the source HTML returned by the POST/GET.
For example I may want to pass a function that checks the headers for a cookie and only returns true if it's found OR pass a regular expression function that checks the source for a piece of content.
I know in PHP or JS I could easily just pass functions as parameters but I am not sure on how to go about it without creating delegates that match the functions I want to use.
I would like the code to be as "generic" as possible so that it could receive any function e.g Pseudocode would be like
public bool MakeHTTPRequest(string url, object possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(object is function){
call object
}
}
}
So the function may OR may NOT be passed in, or I may set a global property with it. Then I need to check IF a function exists and execute it if it does.
The function could be ANYTHING and I want to future proof the code so it can handle any kind of function in the future that maybe passed to it.
Any help would be much appreciated.
Thanks
Use either Func or Action (or Predicate as mentioned by DavidN) to specify the contract of delegates passed as a parameter into your MakeHTTPRequest method.
public bool MakeHTTPRequest(string url, Action possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(possiblefunction != null){
possiblefunction();
}
}
}
If your "function" returns a value/result then use Func instead..(where T is the expected return type)...e.g. Func<int>.
If your "function" expects parameters then specify the expected parameter types. So here are some examples:
Func<string,float,int> - a delegate which expects string and float parameters and returns an int result
Action - a delegate that takes no parameters, and doesn't return a value
Action<string,float> - a delegate that doesn't return a value (void), and expects a string and float as parameters.
http://www.blackwasp.co.uk/FuncAction.aspx
Func vs. Action vs. Predicate
If you're trying to pass back the "response" to the possiblefunction then do something like this.
public bool MakeHTTPRequest(string url, Action<string> possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(possiblefunction != null){
possiblefunction(response);
}
}
}
Based on the examples you've given, it seems that what you really want is to pass in a set of validators to determine if the HTTP response meets certain criteria. This seems to be further corroborated by the fact that your method is returning bool.
A Predicate<T>, or actually a set of Predicates, should encapsulate criteria rules that you pass in to determine whether the request is valid or not.
The signature for a Predicate<T> is bool Predicate<T>(T t) - meaning that it takes in some type and produces a bool
Using an array of predicates, and making sure they all pass, seems to be a pretty future-proof way for what you want to do
public bool MakeHTTPRequest(string url, params Predicate<WebResponse>[] validators)
{
// make HTTP requrest
var request = HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK){
foreach(var validator in validators)
if (!validator(response))
return false;
}
return true;
}
The trick is that the params keyword allows you to call the method passing in [0..any number] of values for the params, so all of the following invocations would work:
MakeHTTPRequest("http://stackoverflow.com");
MakeHTTPRequest("http://stackoverflow.com", r => r.Headers.AllKeys.Contains("CookieHeader"));
MakeHTTPRequest("http://stackoverflow.com", r => r.Headers.AllKeys.Contains("CookieHeader"), r => r.ContentLength < 10000);
Actually I need to know how this line is getting executed.
Example:
Browser("InternetExplorer").Page("Stackoverflow").WebElement("textbox").set "user"
The above lines executes like setting browser to Internet Explorer and finding page "stackoverflow" in it and then finding webelement "textbox" in it and then sets it values to "user". in this way the operation is done.
I want to know how this sequence call are be done. I don't want how browser is set to Internet Explorer and so on.
I need to execute a simple statement like
Fun("add").values("2,3").compute
I need the above line to execute by calling "add" function then values "2,3" are passed as parameter then "compute" add it and the final result should "5" be return.
How to do this? Whether we have to use different class for "Fun" and "values" or we need to implement them as "functions" of same class.
How to process sequence call ?
It is enough to return a reference to an existing object to achieve this effect:
class Operator
{
public:
Operator(const string& opAsStr)
{
...
}
Operator& Values(const string& operands)
{
....
return *this;
}
int Compute() // Compute must be a function, no properties in C++
{
...
}
};
// Usable like this
Operator("Add").Values("2,3").Compute()
By defining more function returning *this you can chain many calls. Note that you could return a value (i.e. Operator instead of a reference, or a const reference depending on your use cases).
You can also return a reference (or value) to an object of another class:
class A
{
public:
void DoSomething()
{
....
}
};
class B
{
public:
A MakeA()
{
return A();
}
};
B().MakeA().DoSomething();
I have a class that tries to get information from web service few times:
public TResult Try(Func<TResult> func, int maxRetries)
{
TResult returnValue = default(TResult);
int numTries = 0;
bool succeeded = false;
while (numTries < maxRetries)
{
try
{
returnValue = func();
succeeded = true;
}
catch (Exception ex)
{
Log(ex,numTries);
}
finally
{
numTries++;
}
if (succeeded)
{
return returnValue;
}
else
{
if (numTries == maxRetries)
{
//ask user what to do
}
}
}
Now after 'if (numTries == maxRetries)' user will be able to chose if he wants to continue trying to get data from web service or cancel.
I want to just open new form when user cancels and stop executing method that called above method. I can't just return null or new object because the method that run this retrier will continue to work and in many cases cause problems.
So basically this looks like this:
someValue = retry.Try(() => webService.method(),maxRetries));
//if user canceled after app wasn't able to get data stop execution as already another form is opened
I could of course check if returned value was null like:
someValue = retry.Try(()=>webService.method(),maxRetries));
if (someValue == null)
return;
But this would mean a lot of changes in the code and I want to avoid it and it would be best if I could do it from Try method.
I can think of two things. You could make sure that TResult is of an Interface type that has a Boolean field that represents a successful request (IsSuccessful or IsValid, etc). If you cannot modify TResult, the other option is to use an Out parameter on your try method to pass another value out.
There is no way to just stop the execution of a method. The first thing that comes to mind though is to throw an exception and catch it from the calling method.
Keep in mind though that you shouldn't ever rely on exceptions to control flow like that.. but if you really can't rewrite the calling method, this may be your only option.
The other option is perhaps having your returned result set a flag (via an interface) to notify the caller that it completed successfully.
What is the difference between saying:
if (abc == "a")
{
// do something here...
return;
}
and the same as above, but without the return keyword?
I am a C# coder and I know that the return keyword followed by a type or variable returns that item, but in the above context, return seems to be just to exit the code block but does it make any functional or performance change on the code?
Thanks
"return" exits from the function, not just the enclosing code block. So if your code block was in the context of a function, like so (I don't know C# so I'm using Java syntax):
int thisIsAFunction(int a) {
if (abc == "a")
{
// do something here...
return 1;
}
// do something else here...
}
if abc == "a" then the "do something else here" will not run. But if you removed the return statement inside the if block, then it would run.
return statement exits the function immediately, so it might have performance benefits as the following code in the function would not be executed at all.
MSDN
The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.
Example
//this would do nothing
public void method()
{
return;
}
//this would return true
//notice the return type of bool this means
//the method expects a true\false value
public bool method2()
{
return true;
}
public void test()
{
if(method2())
method()
}
Now if you ran test method2 would always return true and method1 would just end its processing
The return statement does exit the current method, not just the code block (for/while/if/etc). So it is useful for situations like the following:
public void MyMethod(object myObject)
{
if (myObject == null)
{
return; // exits method.
}
// do something with myObject
}
Additional info: I will point out, that many people prefer to have one exit point in a method, however, it can be useful to do something similar to the example here in some cases. I would always try to find ways to limit the number of return or exit points in your method.
In your case, no - but if you had other code after your 'if' statement that you only wanted to run if your statement was false (e.g. if abc != "a"), then the return allows you to bypass that and exit the function / method.
In a loop or case statement, you can use break to achieve this result. This doesn't work on if statements or code blocks in general though.
And yes, return exits the enclosing function.
Executing the return statement will make the execution jump out of the method. Without the return, it would simply go on with the next statement instead.
Yes, your method does not have return type in this case.
e.g.
public void Foo
{
if (abc == "a")
{
// do something here...
return;
}
// some other code
}
This is to say if abd = "a", then exit the method so that some other code won't be executed.
It can be a cleaner way of writing code. I typically do it in a guard clause at or near the beginning of a method. If you have an error condition, just "return" out of the method. It saves wrapping the rest of your work in an else block. Seems trivial, but it helps to reduce code complexity.