C# में int.Parse या Convert.ToInt32 मेथड का उपयोग करके संख्या के स्ट्रिंग प्रतिनिधित्व को इंटीजर में परिवर्तित करें। यदि स्ट्रिंग को परिवर्तित नहीं किया जा सकता है, तो int.Parse या Convert.ToInt32 मेथड एक एक्सेप्शन लौटाता है।
Convert.ToInt32 null मान की अनुमति देता है, यह कोई त्रुटि नहीं फेंकता। int.Parse null मान की अनुमति नहीं देता, और यह ArgumentNullException त्रुटि फेंकता है।
उदाहरण - वैध स्ट्रिंग
class Program
{
static void Main()
{
int res;
string myStr = "5000";
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
}
आउटपुट
Converting String is a numeric representation: 5000
उदाहरण - Convert.ToInt32 के साथ null
class Program
{
static void Main()
{
int res;
string myStr = null;
res = Convert.ToInt32(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
}
आउटपुट
Converting String is a numeric representation: 0
उदाहरण - int.Parse के साथ null
class Program
{
static void Main()
{
int res;
string myStr = null;
res = int.Parse(myStr);
Console.WriteLine("Converting String is a numeric representation: " + res);
Console.ReadLine();
}
}
आउटपुट
Unhandled exception. System.ArgumentNullException: Value cannot be null.