← Back to C# Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Conversion कैसे करें

Type conversion पानी को एक छोटे cup से बड़े में डालने जैसा है, जो ठीक है, बनाम बड़े से छोटे में, जो गिर सकता है। C# किसी value को एक kind से दूसरे में बदलता है, कभी अपने आप और कभी सिर्फ आपके मांगने पर।

In this page:

  1. Type Conversion
Syntax
csharp
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

markup
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);
    }
}
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. #}
आम गलतियां
  1. किसी बड़े long को (int)x से int में cast करना और एक overflow पाना जो चुपचाप wrap around हो जाता है।
  2. गलत input पर int.Parse का उपयोग करना, जो FormatException फेंकता है; int.TryParse का उपयोग करें।
  3. बिना cast के किसी double को किसी int को assign करना, जो compile नहीं होता।
चैप्टर सारांश
  • var keyword compiler को किसी variable के type को infer करने देता है।
  • int, float, double, decimal, bool, char, और string जैसे types अलग-अलग तरह की values store करते हैं।
  • const fields fixed values रखते हैं, और type conversion किसी value को एक type से दूसरे में बदलता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.