开发者

C# function to return nothing if condition not satisfied

开发者 https://www.devze.com 2023-03-02 16:17 出处:网络
I\'m writing a WPF/C# application, in the application I have this function: private char getLastChar()

I'm writing a WPF/C# application, in the application I have this function:

private char getLastChar()
{
 开发者_JAVA技巧   if (textBox1.Text.Length > 0)
        return textBox1.Text[textBox1.Text.Length - 1];
}

if I keep it like this, I get an error:

MainWindow.getLastChar()': not all code paths return a value

How can I set this to work?


PRE-EDIT:

Given that you've said in the comments that "If the textbox is empty, the program should do nothing", why not just do this:

if (textBox1.Text.Length > 0)
{
    //DO STUFF HERE
}
else
{
    //DO NOTHING HERE
}

If you really need to return a null value, you can use one of these two options:

private char? getLastChar()
{
    if (textBox1.Text.Length > 0)
        return textBox1.Text[textBox1.Text.Length - 1];
    else
        return null;
}

You would use it like this:

char? lastCharInTextBox = getLastChar();
if (lastCharInTextBox == null)
{
    //Do something about empty text box
}
else
{
   char myVar = lastCharInTextBox.Value;
   //Do something with the character inside "myVar"
}

Chars are value types, which means that they cannot be set to null references. Using a question mark will make the char nullable.

Alternatively, you could do the following:

private char getLastChar()
{
    if (textBox1.Text.Length > 0)
        return textBox1.Text[textBox1.Text.Length - 1];
    else
        return 0;
}

This would return a normal char, but would return a null terminator character if the textbox has no text.


Your only return is in a conditional statement.

You must have something being returned outside of that if statement.


What would you like to return if textBox.Text.Length > 0? The function has to return something, but in your example above it only returns if the condition is satisfied, which it may not be.


If you have heard of MVC, you will know that this is something you need to check in the controller. The controller should make sure your text box is not empty and then, the code you have written (and which should be in the model) will be invoked. This is good software engineering practice.

In simple words, check if the TextBox is empty (somewhere else in your code) and then conditionally make a call to getLastChar().

Alternatively, you can check for the length and return null, but you would have to handle the null value at some place eventually. So, check the size of the TextBox before making the function call and get yourself some reusable code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号