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

const Fields कैसे काम करते हैं

एक const permanent marker से लिखी एक value है: आप इसे एक बार सेट करते हैं और यह कभी नहीं बदल सकती। यह हफ़्ते में दिनों की संख्या जैसे facts के लिए perfect है।

In this page:

  1. const Fields
Syntax
csharp
const type ConstantName = value;   // must be known at compile time

const Fields

एक const field एक compile-time constant है — इसकी value compile time पर ज्ञात होनी चाहिए और बाद में कभी नहीं बदल सकती।

readonly के विपरीत, const values compiled code में जहां भी उपयोग हों वहां सीधे substitute हो जाती हैं। const mathematical constants या fixed configuration limits जैसी values के लिए आदर्श है।

Warning: किसी const को किसी method call का result assign नहीं किया जा सकता, क्योंकि इसकी value compile time पर resolvable होनी चाहिए।

उदाहरण: const Fields

markup
using System;

class Program
{
    const double Pi = 3.14159;
    const int MaxRetries = 3;

    static void Main(string[] args)
    {
        Console.WriteLine(Pi);
        Console.WriteLine(MaxRetries);
        Console.WriteLine(Pi * 2 * 5);
    }
}
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. किसी const को declare करने के बाद उसे assign करने की कोशिश करना, जो एक compile error है।
  2. बिना value के, या compile time पर अज्ञात value के साथ, एक const declare करना।
  3. runtime पर compute होनी चाहिए वाली value के लिए const का उपयोग करना, जबकि readonly सही choice है।
🔒

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.