I’m trying to reverse a string through the Windows form but for any reason for loop is giving an exception when I’m executing the code.
System.NullReferenceException: Object reference is not set to an instance of an object
Button_Click event
string input=textBox1.Text;
input=Convert.ToString(Console.ReadLine());
string output="";
if(textBox1.Text=="")
{
MessageBox.Show("Sorry! You have not given any input for perform action");
}
else
{
try{
for(int i=input.Length-1; i>=0; i--)
{
output= output+input[i];
}
textBox2.Text=output;
}
catch(Exception ex)
{
MessageBox.Show(""+ex);
}
}
}
While same logic is working perfectly with console application. I know I’m missing very basic thing but at the moment I’m out of ideas.
In a winform,
Console.ReadLine()returnsnull(because there is no console). Likewise,Convert.ToString((string)null)returnsnull. And you can’t call.Length(in thefor) on anull. Key pieces of code:Also, as a minor point: building up a string via concatenation is very inefficient.