Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# function to return nothing if condition not satisfied

Tags:

c#

wpf

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

private char getLastChar()
{
    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?

like image 599
sikas Avatar asked Mar 05 '26 17:03

sikas


1 Answers

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.

like image 101
Karl Nicoll Avatar answered Mar 08 '26 07:03

Karl Nicoll