You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Hello WorldusingSystem;namespaceMyApp{classProgram{staticvoidMain(string[]args){Console.WriteLine("Hello, World!");}}}// Value Types (stored on stack)boolflag=true;// System.Booleanbyteb=255;// 0-255sbytesb=-128;// -128 to 127shortsh=32767;// -32,768 to 32,767ushortush=65535;// 0-65,535inti=2147483647;// Most common integeruintui=4294967295;// Unsigned intlongl=9223372036854775807;ulongul=18446744073709551615;floatf=3.14f;// 32-bit, suffix fdoubled=3.14159;// 64-bit, defaultdecimalm=19.95m;// 128-bit, for money, suffix mcharc='A';// Unicode character// Reference Types (stored on heap)stringname="John";// Immutable stringobjectobj=123;// Base type of all typesdynamicdyn=123;// Runtime type checking
2. VARIABLES & CONSTANTS
// Declaration & Initializationintage;// Declarationage=25;// Assignmentintscore=100;// Declaration + initializationvarinferred="Hello";// Implicitly typed// ConstantsconstdoublePI=3.14159;// Compile-time constantreadonlyintMAX_USERS;// Runtime constant (can be set in constructor)// Variable scope{intblockScoped=10;// Only accessible inside this block}
3. TYPE CONVERSION & CASTING
// Implicit casting (safe, no data loss)intnum=100;doublednum=num;// int to double// Explicit casting (may lose data)doublepi=3.14;intintPi=(int)pi;// 3 (truncated)// Using Convert classstringnumStr="123";intparsed=Convert.ToInt32(numStr);doublefromInt=Convert.ToDouble(42);boolfromString=Convert.ToBoolean("true");// Parse and TryParseintresult=int.Parse("456");boolsuccess=int.TryParse("789",outintsafeResult);// Boxing & Unboxingobjectboxed=42;// Boxing (value β reference)intunboxed=(int)boxed;// Unboxing (reference β value)
// For loopfor(inti=0;i<10;i++){Console.WriteLine(i);}// Foreach loopint[]numbers={1,2,3,4,5};foreach(intnuminnumbers){Console.WriteLine(num);}// While loopintcount=0;while(count<5){Console.WriteLine(count);count++;}// Do-while (executes at least once)intx=10;do{Console.WriteLine(x);x++;}while(x<5);// Loop controlbreak;// Exit loop immediatelycontinue;// Skip to next iterationreturn;// Exit methodgotolabel;// Jump to labeled statement (avoid if possible)
9. METHODS
// Basic methodpublicintAdd(inta,intb){returna+b;}// Void methodpublicvoidGreet(stringname){Console.WriteLine($"Hello, {name}");}// Optional parameterspublicvoidLog(stringmessage,stringprefix="INFO"){Console.WriteLine($"[{prefix}] {message}");}// Named argumentsLog(message:"Started",prefix:"DEBUG");// Reference parameters (ref)publicvoidIncrement(refintvalue){value++;}intnum=5;Increment(refnum);// num is now 6// Output parameters (out)publicboolTryDivide(inta,intb,outintresult){if(b!=0){result=a/b;returntrue;}result=0;returnfalse;}// In parameter (read-only reference)publicvoidDisplay(inintvalue){// Cannot modify valueConsole.WriteLine(value);}// Params keyword (variable arguments)publicintSum(paramsint[]numbers){returnnumbers.Sum();}inttotal=Sum(1,2,3,4,5);// Method overloadingpublicintMultiply(inta,intb)=>a*b;publicdoubleMultiply(doublea,doubleb)=>a*b;// Local functionsintOuterMethod(){intLocalFunction(intx)=>x*2;returnLocalFunction(5);}// Expression-bodied memberpublicintSquare(intx)=>x*x;
10. CLASSES & OOP
// Basic classpublicclassPerson{// Fields (private by convention)privatestring_name;privateint_age;// ConstructorpublicPerson(stringname,intage){_name=name;_age=age;}// Default constructor (auto-implemented if no constructors)publicPerson(){}// Constructor chainingpublicPerson(stringname):this(name,0){}// MethodspublicvoidIntroduce(){Console.WriteLine($"I'm {_name}, {_age} years old");}// Static methodpublicstaticvoidSayHello(){Console.WriteLine("Hello!");}// Destructor (rarely used)~Person(){// Cleanup code}}// Access modifiers// public - Any code can access// private - Only within the same class// protected - Within class and derived classes// internal - Within same assembly// protected internal - Same assembly or derived classes// private protected - Same assembly AND derived classes// Using the classPersonjohn=newPerson("John",30);john.Introduce();Person.SayHello();
11. INHERITANCE & POLYMORPHISM
// Base classpublicclassAnimal{publicstringName{get;set;}publicvirtualvoidMakeSound()// Virtual allows override{Console.WriteLine("Some sound");}publicvoidEat(){Console.WriteLine("Eating...");}}// Derived classpublicclassDog:Animal{publicstringBreed{get;set;}publicoverridevoidMakeSound()// Override virtual method{Console.WriteLine("Woof!");}publicnewvoidEat()// Hide base method (rarely used){Console.WriteLine("Dog eating...");}}// Sealed class (cannot be inherited from)publicsealedclassMathHelper{// methods}// PolymorphismAnimalmyDog=newDog();myDog.MakeSound();// Calls Dog's MakeSound() (polymorphic)// Type checkingif(myDogisDog){Dogd=(Dog)myDog;// Explicit cast}Dogd2=myDogasDog;// Safe cast (null if fails)if(d2!=null){}// Calling base constructorpublicclassCat:Animal{publicCat(stringname):base()// Call base constructor{Name=name;}protectedoverridevoidMakeSound()// Protected override{base.MakeSound();// Call base implementationConsole.WriteLine("Meow!");}}
12. INTERFACES & ABSTRACT CLASSES
// Interface (contract)publicinterfaceIPrintable{voidPrint();// No implementationstringName{get;set;}// Property}// Interface with default implementation (C# 8+)publicinterfaceILogger{voidLog(stringmessage);voidLogError(stringerror)// Default implementation{Log($"ERROR: {error}");}}// Multiple interface implementationpublicclassDocument:IPrintable,ILogger{publicstringName{get;set;}publicvoidPrint(){Console.WriteLine($"Printing {Name}");}publicvoidLog(stringmessage){Console.WriteLine($"Log: {message}");}}// Abstract class (partial implementation)publicabstractclassShape{publicabstractdoubleGetArea();// Must be implementedpublicvirtualstringGetColor()// Optional override{return"Red";}publicvoidDisplay()// Concrete method{Console.WriteLine($"Area: {GetArea()}");}}publicclassCircle:Shape{publicdoubleRadius{get;set;}publicoverridedoubleGetArea(){returnMath.PI*Radius*Radius;}}
13. PROPERTIES & INDEXERS
// Auto-implemented propertypublicclassProduct{publicstringName{get;set;}publicdecimalPrice{get;set;}}// Full property with backing fieldpublicclassCustomer{privatestring_name;publicstringName{get{return_name;}set{if(string.IsNullOrEmpty(value))thrownewArgumentException("Name cannot be empty");_name=value;}}}// Read-only propertypublicclassSettings{publicstaticstringAppName{get;}="MyApp";}// Computed propertypublicclassRectangle{publicdoubleWidth{get;set;}publicdoubleHeight{get;set;}publicdoubleArea=>Width*Height;// Expression-bodied}// Init-only property (C# 9+)publicclassPerson{publicstringName{get;init;}// Can only be set during initialization}varp=newPerson{Name="Alice"};// OK// p.Name = "Bob"; // Error!// Required properties (C# 11+)publicclassEmployee{publicrequiredintId{get;set;}publicrequiredstringName{get;set;}}// var e = new Employee { Name = "John" }; // Error: Id missing// IndexerspublicclassShoppingCart{privateList<Product>_products=newList<Product>();publicProductthis[intindex]{get=>_products[index];set=>_products[index]=value;}publicProductthis[stringname]{get=>_products.FirstOrDefault(p =>p.Name==name);}}varcart=newShoppingCart();cart[0]=newProduct();varproduct=cart[0];
14. STRUCTS & ENUMS
// Struct (value type, lightweight)publicstructPoint{publicintX{get;set;}publicintY{get;set;}publicPoint(intx,inty){X=x;Y=y;}publicdoubleDistanceTo(Pointother){returnMath.Sqrt(Math.Pow(X-other.X,2)+Math.Pow(Y-other.Y,2));}}// Using structPointp1=newPoint(0,0);Pointp2=newPoint(3,4);doubledistance=p1.DistanceTo(p2);// Record struct (C# 10+)publicrecordstructColor(intR,intG,intB);// EnumpublicenumDaysOfWeek{Monday,// 0Tuesday,// 1Wednesday,// 2Thursday,// 3Friday,// 4Saturday,// 5Sunday// 6}publicenumHttpStatus{OK=200,BadRequest=400,Unauthorized=401,NotFound=404}// Using enumsDaysOfWeektoday=DaysOfWeek.Wednesday;intdayValue=(int)today;// 2stringdayName=today.ToString();// "Wednesday"DaysOfWeekparsed=Enum.Parse<DaysOfWeek>("Monday");boolisValid=Enum.IsDefined(typeof(DaysOfWeek),5);// true// Flags enum[Flags]publicenumPermissions{None=0,Read=1,Write=2,Execute=4,All=Read|Write|Execute}Permissionsperms=Permissions.Read|Permissions.Write;boolcanRead=perms.HasFlag(Permissions.Read);// true
15. EXCEPTION HANDLING
// Try-catch-finallytry{intresult=10/int.Parse("0");}catch(DivideByZeroExceptionex){Console.WriteLine($"Cannot divide by zero: {ex.Message}");}catch(FormatExceptionex)when(ex.Message.Contains("invalid")){Console.WriteLine("Format exception with filter");}catch(Exceptionex)// Generic catch (last){Console.WriteLine($"Unexpected error: {ex.Message}");throw;// Re-throw exception preserving stack trace}finally{Console.WriteLine("Always executes (cleanup)");}// Throwing exceptionspublicvoidValidateAge(intage){if(age<0)thrownewArgumentException("Age cannot be negative",nameof(age));if(age>150)thrownewArgumentOutOfRangeException(nameof(age),"Age too high");if(age<18)thrownewInvalidOperationException("User must be 18 or older");}// Custom exceptionpublicclassInvalidUserException:Exception{publicstringUsername{get;}publicInvalidUserException(stringusername):base($"User '{username}' is invalid"){Username=username;}publicInvalidUserException(stringusername,Exceptioninner):base($"User '{username}' is invalid",inner){Username=username;}}// Using statement for disposable objectsusing(varfile=newSystem.IO.StreamReader("file.txt")){stringcontent=file.ReadToEnd();}// Automatically calls Dispose()// Using declaration (C# 8+)usingvarfile2=newSystem.IO.StreamReader("file.txt");stringcontent2=file2.ReadToEnd();// Disposed at end of scope
16. DELEGATES & EVENTS
// Delegate declarationpublicdelegateintMathOperation(inta,intb);// Using delegatepublicclassCalculator{publicintAdd(inta,intb)=>a+b;publicstaticintMultiply(inta,intb)=>a*b;publicvoidExecute(){MathOperationop=Add;// Instance methodop+=Multiply;// Multicastop+=(a,b)=>a-b;// Lambdaintresult=op(5,3);// All methods execute// Last method's result is returned}}// Func, Action, Predicate delegatesFunc<int,int,int>add=(a,b)=>a+b;Action<string>print=(msg)=>Console.WriteLine(msg);Predicate<int>isEven=(x)=>x%2==0;// EventspublicclassButton{// Event declarationpubliceventEventHandlerClicked;publiceventEventHandler<CustomEventArgs>CustomEvent;protectedvirtualvoidOnClicked(){Clicked?.Invoke(this,EventArgs.Empty);// Null-conditional invoke}publicvoidSimulateClick(){OnClicked();}}// Custom event argspublicclassCustomEventArgs:EventArgs{publicstringMessage{get;set;}publicCustomEventArgs(stringmsg)=>Message=msg;}// Subscribing to eventsButtonbtn=newButton();btn.Clicked+=(sender,e)=>Console.WriteLine("Button clicked");btn.Clicked+=Button_ClickHandler;// Named methodvoidButton_ClickHandler(objectsender,EventArgse){Console.WriteLine("Handler called");}// Unsubscribingbtn.Clicked-=Button_ClickHandler;
17. LINQ
usingSystem.Linq;// Data sourceint[]numbers={1,2,3,4,5,6,7,8,9,10};varpeople=newList<Person>{newPerson{Name="Alice",Age=30},newPerson{Name="Bob",Age=25},newPerson{Name="Charlie",Age=35}};// Query syntaxvarevenNumbers=fromninnumberswheren%2==0
orderby n descending
selectn;varadultNames=frompinpeoplewherep.Age>=18
orderby p.Nameselectp.Name;// Method syntax (fluent)varevenNumbers2=numbers.Where(n =>n%2==0).OrderByDescending(n =>n).Select(n =>n);// Common LINQ methodsvarfiltered=people.Where(p =>p.Age>25);varprojected=people.Select(p =>new{p.Name,p.Age});varordered=people.OrderBy(p =>p.Age).ThenBy(p =>p.Name);varorderedDesc=people.OrderByDescending(p =>p.Age);varfirstMatch=people.First(p =>p.Age>30);varfirstOrDefault=people.FirstOrDefault(p =>p.Age>100);varsingle=people.Single(p =>p.Age==25);// Throws if not exactly onevarany=people.Any(p =>p.Age>40);varall=people.All(p =>p.Age>=0);varcontains=numbers.Contains(5);varcount=people.Count(p =>p.Age>20);varsum=numbers.Sum();varmin=numbers.Min();varmax=numbers.Max();varaverage=numbers.Average();vargrouped=people.GroupBy(p =>p.Age/10);vardistinct=numbers.Distinct();varunion=numbers.Union(new[]{11,12});varintersect=numbers.Intersect(new[]{5,6,7,11});varexcept=numbers.Except(new[]{1,2,3});varskip=numbers.Skip(5);vartake=numbers.Take(5);varskipTake=numbers.Skip(2).Take(3);varzip=numbers.Zip(new[]{"A","B","C"},(n,s)=>$"{n}:{s}");// Aggregationsvaraggregate=numbers.Aggregate((acc,n)=>acc+n);varjoin=people.Join(numbers, p =>p.Age, n =>n,(p,n)=>new{p.Name,Number=n});// Deferred vs immediate executionvardeferred=numbers.Where(n =>n>5);// Not executed yetvarimmediate=numbers.Where(n =>n>5).ToList();// Executed now// To collectionsList<int>numList=numbers.ToList();int[]numArray=numbers.ToArray();Dictionary<int,string>dict=people.ToDictionary(p =>p.Age, p =>p.Name);varlookup=people.ToLookup(p =>p.Age/10);
18. FILE I/O
usingSystem.IO;usingSystem.Text;// Read all textstringcontent=File.ReadAllText("file.txt");string[]lines=File.ReadAllLines("file.txt");// Write all textFile.WriteAllText("output.txt","Hello World");File.WriteAllLines("output.txt",new[]{"Line 1","Line 2"});File.AppendAllText("log.txt","New entry\n");// Using StreamReaderusing(StreamReaderreader=newStreamReader("file.txt")){stringline;while((line=reader.ReadLine())!=null){Console.WriteLine(line);}}// Using StreamWriterusing(StreamWriterwriter=newStreamWriter("output.txt")){writer.WriteLine("Hello");writer.Write("World");}// Binary filesusing(BinaryWriterwriter=newBinaryWriter(File.Open("data.bin",FileMode.Create))){writer.Write(123);writer.Write(3.14);writer.Write("Text");}using(BinaryReaderreader=newBinaryReader(File.Open("data.bin",FileMode.Open))){intnum=reader.ReadInt32();doubledbl=reader.ReadDouble();stringtext=reader.ReadString();}// File infoFileInfofileInfo=newFileInfo("file.txt");boolexists=fileInfo.Exists;longsize=fileInfo.Length;DateTimemodified=fileInfo.LastWriteTime;fileInfo.CopyTo("backup.txt");fileInfo.MoveTo("newfolder/file.txt");fileInfo.Delete();// Directory operationsDirectory.CreateDirectory("MyFolder");string[]files=Directory.GetFiles("C:\\MyFolder");string[]subdirs=Directory.GetDirectories("C:\\MyFolder");string[]allFiles=Directory.GetFiles("C:\\MyFolder","*.txt",SearchOption.AllDirectories);Directory.Delete("MyFolder",recursive:true);// Path helpersstringcombined=Path.Combine("folder","subfolder","file.txt");stringfileName=Path.GetFileName("C:\\folder\\file.txt");// "file.txt"stringextension=Path.GetExtension("file.txt");// ".txt"stringnameWithoutExt=Path.GetFileNameWithoutExtension("file.txt");// "file"stringfullPath=Path.GetFullPath("file.txt");stringtempFile=Path.GetTempFileName();stringtempPath=Path.GetTempPath();
19. ASYNCHRONOUS PROGRAMMING
usingSystem.Threading.Tasks;// Async method signaturepublicasyncTask<string>DownloadDataAsync(stringurl){using(HttpClientclient=newHttpClient()){stringresult=awaitclient.GetStringAsync(url);returnresult;}}// Calling async methodpublicasyncTaskProcessDataAsync(){stringdata=awaitDownloadDataAsync("https://example.com");Console.WriteLine(data);}// Async void (only for event handlers)publicasyncvoidButton_Click(objectsender,EventArgse){awaitTask.Delay(1000);Console.WriteLine("After delay");}// Parallel executionpublicasyncTaskProcessMultipleAsync(){Task<string>task1=DownloadDataAsync("https://api1.com");Task<string>task2=DownloadDataAsync("https://api2.com");// Wait for allawaitTask.WhenAll(task1,task2);stringresult1=task1.Result;stringresult2=task2.Result;// Wait for anyTask<string>completed=awaitTask.WhenAny(task1,task2);stringfirstResult=awaitcompleted;}// Task.Run for CPU-bound workpublicasyncTask<int>CalculateAsync(){returnawaitTask.Run(()=>{// CPU-intensive workintsum=0;for(inti=0;i<1000000;i++)sum+=i;returnsum;});}// CancellationpublicasyncTask<string>DownloadWithCancellationAsync(stringurl,CancellationTokentoken){using(HttpClientclient=newHttpClient()){varresponse=awaitclient.GetAsync(url,token);returnawaitresponse.Content.ReadAsStringAsync();}}// Using cancellationvarcts=newCancellationTokenSource();cts.CancelAfter(5000);// Cancel after 5 secondstry{stringresult=awaitDownloadWithCancellationAsync("https://example.com",cts.Token);}catch(OperationCanceledException){Console.WriteLine("Operation cancelled");}// Progress reportingpublicasyncTaskProcessWithProgressAsync(IProgress<int>progress){for(inti=0;i<=100;i++){awaitTask.Delay(50);progress?.Report(i);}}varprogress=newProgress<int>(p =>Console.WriteLine($"{p}% complete"));awaitProcessWithProgressAsync(progress);// ConfigureAwait (avoid deadlocks in UI apps)stringdata=awaitDownloadDataAsync(url).ConfigureAwait(false);// ValueTask (for performance)publicasyncValueTask<int>GetCachedValueAsync(){if(cachedValue.HasValue)returncachedValue.Value;cachedValue=awaitFetchValueAsync();returncachedValue.Value;}
20. ATTRIBUTES & REFLECTION
// Custom attribute[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=true)]publicclassAuthorAttribute:Attribute{publicstringName{get;}publicstringVersion{get;set;}publicAuthorAttribute(stringname){Name=name;}}// Using attributes[Author("John Doe",Version="1.0")][Author("Jane Smith")]publicclassSampleClass{[Author("John Doe")]publicvoidMyMethod(){}}// Predefined attributes[Obsolete("Use NewMethod instead")]publicvoidOldMethod(){}[Serializable]publicclassMyData{}[Conditional("DEBUG")]publicvoidDebugOnlyMethod(){}// ReflectionusingSystem.Reflection;Typetype=typeof(string);TypepersonType=newPerson().GetType();TypeloadedType=Type.GetType("System.String");// Get membersMemberInfo[]members=type.GetMembers();MethodInfo[]methods=type.GetMethods();PropertyInfo[]properties=type.GetProperties();FieldInfo[]fields=type.GetFields();ConstructorInfo[]constructors=type.GetConstructors();// Invoke methodsMethodInfomethod=typeof(Math).GetMethod("Pow");objectresult=method.Invoke(null,newobject[]{2.0,3.0});// 8.0// Create instanceTypelistType=typeof(List<int>);objectlist=Activator.CreateInstance(listType);MethodInfoaddMethod=listType.GetMethod("Add");addMethod.Invoke(list,newobject[]{42});// Get attributesvarattributes=typeof(SampleClass).GetCustomAttributes(typeof(AuthorAttribute),false);foreach(AuthorAttributeattrinattributes){Console.WriteLine($"Author: {attr.Name}");}// Dynamic invocation with reflectionpublicobjectCallMethod(stringclassName,stringmethodName,object[]parameters){Typetype=Type.GetType(className);objectinstance=Activator.CreateInstance(type);MethodInfomethod=type.GetMethod(methodName);returnmethod.Invoke(instance,parameters);}
21. NULLABLE TYPES & NULL SAFETY
// Nullable value typesint?nullableInt=null;bool?nullableBool=null;DateTime?nullableDate=null;// Check if has valueif(nullableInt.HasValue){intvalue=nullableInt.Value;// Throws if null}// Safe accessintsafeValue=nullableInt??0;// Default if nullintanotherSafe=nullableInt.GetValueOrDefault(-1);// Nullable reference types (C# 8+)
#nullable enable
string?nullableString=null;// Can be nullstringnonNullableString="Hello";// Cannot be null// Null-forgiving operator (override warnings)stringforced=nullableString!;// Suppress warning// Null-conditional operatorsint?length=nullableString?.Length;Person?person=GetPerson();stringname=person?.Name??"Unknown";// Null coalescing assignment (C# 8+)person??=newPerson("Default",0);// Pattern matching with nullif(personis not null){Console.WriteLine(person.Name);}// Generic nullabilitypublicT?GetDefault<T>()whereT:struct// T? means Nullable<T>{returnnull;}publicT?GetDefaultRef<T>()whereT:class// T? can be null{returnnull;}
#nullable restore
// Annotation contexts
#nullable disable // Turn off nullable checks
#nullable enable // Turn on nullable checks
#nullable restore // Restore to project default// Required member (C# 11)publicclassProduct{publicrequiredstringName{get;set;}publicdecimalPrice{get;set;}=0;}// var p = new Product(); // Error: Name required
22. RECORDS (C# 9+)
// Basic record (reference type)publicrecordPerson{publicstringFirstName{get;init;}publicstringLastName{get;init;}}// Positional record (auto-generated properties)publicrecordPoint(intX,intY);// Using recordsvarp1=newPerson{FirstName="John",LastName="Doe"};varp2=newPoint(10,20);// With-expression (non-destructive mutation)varp3=p1with{FirstName="Jane"};varp4=p2with{X=30};// Value-based equalityvarperson1=newPerson{FirstName="Alice",LastName="Smith"};varperson2=newPerson{FirstName="Alice",LastName="Smith"};boolareEqual=person1==person2;// true (by value, not reference)// Record struct (C# 10+)publicrecordstructColor(intR,intG,intB);// Record with methodspublicrecordProduct{publicstringName{get;init;}publicdecimalPrice{get;init;}publicdecimalCalculateTax(decimaltaxRate)=>Price*taxRate;// Custom equalitypublicvirtualboolEquals(Productother){returnName==other.Name;}}// Inheritance with recordspublicrecordAnimal(stringName);publicrecordDog(stringName,stringBreed):Animal(Name);// JSON serialization friendlyvarrecord=newPerson{FirstName="John",LastName="Doe"};stringjson=System.Text.Json.JsonSerializer.Serialize(record);vardeserialized=System.Text.Json.JsonSerializer.Deserialize<Person>(json);
23. PATTERN MATCHING (C# 7-11)
// Type patternobjectobj="Hello";if(objisstrings){Console.WriteLine($"String length: {s.Length}");}// Switch expression pattern (C# 8+)stringGetTypeName(objectobj)=>objswitch{inti=>$"Integer: {i}",strings=>$"String: {s}",doubled=>$"Double: {d}",null=>"Null",
_ =>"Unknown"};// Property patternif(personis{Age:>18,Name:stringname}){Console.WriteLine($"{name} is adult");}// Tuple patternstringGetQuadrant(Pointp)=>(p.X,p.Y)switch{(>0,>0)=>"Q1",(<0,>0)=>"Q2",(<0,<0)=>"Q3",(>0,<0)=>"Q4",(0,_)=>"On Y axis",(_,0)=>"On X axis",
_ =>"Origin"};// Positional patternpublicrecordPoint2D(intX,intY);stringDescribe(Point2Dpoint)=>pointswitch{(0,0)=>"Origin",(varx,0)=>$"On X axis at {x}",(0,vary)=>$"On Y axis at {y}",var(x,y)=>$"At ({x}, {y})"};// Relational pattern (C# 9+)stringGetGrade(intscore)=>scoreswitch{>=90=>"A",>=80=>"B",>=70=>"C",>=60=>"D",<60=>"F"};// Logical patterns (C# 9+)boolIsValidAge(intage)=>ageis>=0 and <=150;boolIsTeenager(intage)=>ageis>=13 and <=19;boolIsValidChar(charc)=>cis not '\0';// List patterns (C# 11+)int[]numbers={1,2,3,4,5};stringDescribeArray(int[]arr)=>arrswitch{[]=>"Empty",[varfirst]=>$"Single element: {first}",[varfirst,varsecond]=>$"Two elements: {first}, {second}",[varfirst, ..,varlast]=>$"Starts with {first}, ends with {last}",[1,2, ..]=>"Starts with 1,2",[..,5]=>"Ends with 5",
_ =>"Other"};// Var patternif(int.TryParse(input,outvarresult)){Console.WriteLine($"Parsed: {result}");}
24. TOP-LEVEL STATEMENTS (C# 9+)
// Entire program without namespace, class, MainusingSystem;usingSystem.Linq;Console.WriteLine("Hello World!");// Variablesstringname="John";intage=30;// Methods can be definedvoidGreet(stringperson){Console.WriteLine($"Hello, {person}");}Greet(name);// Can return exit code// return 0;// Can use async// await Task.Delay(1000);// Can access command line argsif(args.Length>0){Console.WriteLine($"Args: {string.Join(", ",args)}");}// Traditional Main equivalent// args variable is availableforeach(vararginargs){Console.WriteLine(arg);}
π QUICK REFERENCE CARD
Category
Syntax Example
Write to console
Console.WriteLine("text")
Read from console
string input = Console.ReadLine()
Parse string to int
int.Parse("123") or int.TryParse("123", out int result)
String interpolation
$"Value: {x}"
List creation
new List<int> { 1, 2, 3 }
Dictionary
new Dictionary<string, int>()
Exception
try { } catch (Exception ex) { } finally { }
Async method
async Task<T> MethodName()
Wait for task
await task
LINQ query
from x in collection where x > 5 select x
Lambda
(x, y) => x + y
Null check
if (obj is null)
Pattern matching
obj is string s
Property with validation
public int Prop { get => _prop; set => _prop = value > 0 ? value : 0; }
Constructor
public ClassName(parameters) : base(param) { }
π§ COMMON NAMING CONVENTIONS
Element
Convention
Example
Namespaces
PascalCase
System.Collections
Classes
PascalCase
CustomerService
Interfaces
I + PascalCase
IRepository
Methods
PascalCase
CalculateTotal()
Properties
PascalCase
FirstName
Fields (private)
_camelCase
_customerId
Parameters
camelCase
firstName
Local variables
camelCase
itemCount
Constants
PascalCase
MaxRetryCount
About
Complete reference covering syntax, types, OOP, LINQ, async/await, collections, exceptions, file I/O, pattern matching, records, and more. Includes 24 sections with practical examples.