Expression-Bodied Members क्या हैं
Expression-bodied members छोटे methods और properties लिखने का एक-line तरीका है, जैसे एक पूरे essay के बजाय एक तुरंत जवाब। वे result देने के लिए एक arrow उपयोग करते हैं।
In this page:
Syntax
public ReturnType MethodName() => expression;
public type PropertyName => expression;
public ClassName(type parameter) => field = parameter;
Expression-Bodied Members
Expression-bodied members आपको एक method, property, या constructor लिखने देते हैं जिसकी पूरी body एक return वाले पूरे { } block के बजाय => उपयोग करते हुए एक single expression है।
यह one-line members के लिए सिर्फ एक syntactic shortcut है और behavior नहीं बदलता। यह simple properties और छोटे computed methods के लिए व्यापक रूप से उपयोग होता है।
Note:
Expression-bodied syntax methods, read-only properties, और यहां तक कि constructors और finalizers के लिए भी काम करता है — सिर्फ fields के लिए नहीं।
उदाहरण: Expression-Bodied Members
using System;
class Circle
{
public double Radius;
public Circle(double radius) => Radius = radius;
public double Area => Math.PI * Radius * Radius;
public double Diameter() => Radius * 2;
}
class Program
{
static void Main(string[] args)
{
Circle c = new Circle(4);
Console.WriteLine(c.Area);
Console.WriteLine(c.Diameter());
}
}
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. #}
आम गलतियां
public double Area => Math.PI * Radius * Radius;को{ get; } = ...के साथ confuse करना;=>version हर access पर फिर से calculate करता है बजाय एक बार value store करने के।=>के बाद कई statements रखने की कोशिश करना, जबकि एक expression-bodied member सिर्फ एक single expression की अनुमति देता है; एक normal{ }body उपयोग करें।- किसी expression-bodied property से setter की उम्मीद करना, जबकि किसी property पर
=>एक read-only getter बनाता है।
चैप्टर सारांश
- Records immutable data types define करते हैं, और tuples व deconstruction values को group और unpack करते हैं।
- Pattern matching values और shapes को संक्षेप में जांचता है।
- Nullable reference types और expression-bodied members code को सुरक्षित और छोटा बनाते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: