2
Answers

Object reference not set to an instance of an object

Janaki Ram

Janaki Ram

7y
198
1
Hi All,
 
Can anyone one help me to rectify the error for the blow code for String type.
If i pass string directly it is working but if i  mention string value1= Console.ReadLine(); not executing.
 
error:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at Program.Main () [0x0000c] in :0 [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object at Program.Main () [0x0000c] in :0  
 
C# code:
 
using System;
public class Program
{
public static void Main()
{
int sp = 0;
int ws = 0;
int di = 0;
string value1= Console.ReadLine();
foreach (char c in value1)
{
if (!char.IsLetterOrDigit(c))
{ sp++;
if(char.IsWhiteSpace(c))
{
sp--;
}
}
if (char.IsWhiteSpace(c))
{ ws++;
}
if (char.IsDigit(c))
{ di++;
}
}
Console.WriteLine("special "+sp);
Console.WriteLine("white "+ws);
Console.WriteLine("digit "+di);
}
}
Answers (2)
0
Midhun T P

Midhun T P

NA 19.7k 281.1k 7y
Hi,
 
If you are running this code in a console application, this won't throw any error.
I think you are running this code in windows forms application.
 
Console.Readline() wont work in windows forms. 
0
Bryian Tan

Bryian Tan

NA 9.4k 887.2k 7y
The code seem fine. I don't see anny error. https://dotnetfiddle.net/LunW1F