← Back to C# Course | Chapter 6: OOP Basics | Lesson 6 of 7

Static Members क्या हैं

Static members एक object के बजाय पूरी class से belong करते हैं, जैसे school की घंटी जो सबके लिए बजती है। आप उन्हें बिना कोई object बनाए class name के ज़रिए उपयोग करते हैं।

In this page:

  1. Static Members
Syntax
csharp
class ClassName
{
    public static type Field;
    public static ReturnType MethodName() { }
}

ClassName.Field;
ClassName.MethodName();   // no object needed

Static Members

static fields और methods खुद class से belong करते हैं, किसी individual object से नहीं, और हर instance में share होते हैं। आप उन्हें किसी object reference के बजाय class name के ज़रिए call करते हैं।

Static members counters, utility methods, और shared configuration के लिए उपयोगी हैं।

Note: यह गिनने का एक अच्छा तरीका है कि किसी class के कितने instances बन चुके हैं, एक static field का उपयोग करके।

उदाहरण: Static Members

markup
using System;

class Counter
{
    public static int InstanceCount = 0;

    public Counter()
    {
        InstanceCount++;
    }

    public static int Double(int n) => n * 2;
}

class Program
{
    static void Main(string[] args)
    {
        new Counter();
        new Counter();
        new Counter();

        Console.WriteLine(Counter.InstanceCount);
        Console.WriteLine(Counter.Double(21));
    }
}
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. बिना किसी object के किसी static method से एक instance member access करने की कोशिश करना।
  2. यह उम्मीद करना कि हर object की किसी static field की अपनी copy होगी, जबकि यह सबके बीच share होती है।
  3. हर जगह static उपयोग करना, जो code को test करना मुश्किल बनाता है।
🔒

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.