Type Conversion कैसे करें
Type conversion पानी को एक छोटे cup से बड़े में डालने जैसा है, जो ठीक है, बनाम बड़े से छोटे में, जो गिर सकता है। C# किसी value को एक kind से दूसरे में बदलता है, कभी अपने आप और कभी सिर्फ आपके मांगने पर।
In this page:
Syntax
double widened = wholeNumber; // implicit
int narrowed = (int)decimalValue; // explicit cast
int parsed = int.Parse(text);
Convert.ToInt32(text);
Type Conversion
C# compatible types के बीच या तो implicitly (widening, जैसे int से double) या explicitly एक cast के साथ (narrowing, जैसे double से int) convert करता है।
Convert class और Parse/TryParse methods strings को numbers में सुरक्षित रूप से convert करना handle करते हैं। Explicit narrowing casts सावधान न रहने पर चुपचाप data खो सकते हैं।
Warning:
9.9 जैसे किसी double को int में cast करना इसे 9 तक truncate कर देता है — यह round नहीं करता।उदाहरण: Type Conversion
using System;
class Program
{
static void Main(string[] args)
{
int wholeNumber = 10;
double asDouble = wholeNumber; // implicit widening
double preciseValue = 9.9;
int truncated = (int)preciseValue; // explicit narrowing
string numericText = "42";
int parsed = int.Parse(numericText);
Console.WriteLine(asDouble);
Console.WriteLine(truncated);
Console.WriteLine(parsed + 8);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी बड़े
longको(int)xसेintमें cast करना और एक overflow पाना जो चुपचाप wrap around हो जाता है। - गलत input पर
int.Parseका उपयोग करना, जोFormatExceptionफेंकता है;int.TryParseका उपयोग करें। - बिना cast के किसी
doubleको किसीintको assign करना, जो compile नहीं होता।
चैप्टर सारांश
varkeyword compiler को किसी variable के type को infer करने देता है।int,float,double,decimal,bool,char, औरstringजैसे types अलग-अलग तरह की values store करते हैं।constfields fixed values रखते हैं, और type conversion किसी value को एक type से दूसरे में बदलता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: