In this blog, I will explore the top useful C# .NET snippets that every developer should have in their arsenal. From object initialization syntax to dictionary initialization, these snippets cover a wide range of functionalities that will help you streamline your C# development process. Object Initialization Syntax - By using object initialization syntax, you can quickly create and initialize objects without the need for multiple lines of code. public class Product { public string Name { get; set; } public decimal Price { get; set; } } var product = new Product { Name = "Mouse", Price = 999.00 }; Enumerable.Range Method - This snippet simplifies the process of iterating over a range of numbers in a concise and readable manner. foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine(number); } Conditional Ternary Operator - By using the conditional ternary operator, you can streamline conditional checks and make your code more compact and readable. int time = 7; var result = (time < 5) ? "Weekend" : "Working"; Console.WriteLine(result); Task.WhenAll Method - With Task.WhenAll, you can improve the performance of your asynchronous operations by running them concurrently. async Task DownloadAllAsync(List<string> urls) { var tasks = urls.Select(url => DownloadAsync(url)).ToArray(); await Task.WhenAll(tasks); } async Task DownloadAsync(string url) { Console.WriteLine($"Downloading from {url}"); } Null-Conditional Operator - By using the null-conditional operator, you can handle null values gracefully and prevent runtime exceptions in your code. string firstName = person?.FirstName ?? "Unknown"; Console.WriteLine(firstName); LINQ Query Syntax - By leveraging LINQ query syntax, you can write complex queries on collections with ease and readability. var scores = new int[] { 90, 100, 82, 89, 92 }; var highScores = from score in scores where score >= 90 select score; foreach (var score in highScores) { Console.WriteLine(score); } Using Statement - The using statement is essential for handling disposable objects and preventing resource leaks in your code. using (var streamReader = new StreamReader(@"C:\file.txt")) { string content = streamReader.ReadToEnd(); Console.WriteLine(content); } Expression-Bodied Members - By using expression-bodied members, you can make your code more concise and expressive, especially for simple properties and methods. public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{FirstName} {LastName}"; // Fullname directly dynamically set at model level. } Dictionary Initialization - Dictionary initialization simplifies the process of populating key-value pairs in a dictionary with a clean and readable syntax. var capitals = new Dictionary<string, string> { ["USA"] = "Washington, D.C.", ["Japan"] = "Tokyo", ["India"] = "Delhi" }; Appending an Element to a List - C# offers numerous methods for adding items to lists. For instance, the widely-used Add() method is available. However, there are plenty of other options as well. Here are five: // Statically defined list List<int> myList = new List<int> {2, 5, 6}; // Appending using Add() myList.Add(5); // [2, 5, 6, 5] // Appending using AddRange() myList.AddRange(new List<int> {9}); // [2, 5, 6, 5, 9] // Appending using Insert() myList.Insert(myList.Count, -4); // [2, 5, 6, 5, 9, -4] // Appending using InsertRange() myList.InsertRange(myList.Count, new List<int> {3}); // [2, 5, 6, 5, 9, -4, 3] // To Check if a List Is Empty List<int> myList = new List<int>(); // Check if a list is empty by its Count if (myList.Count == 0) { // the list is empty } // Check if a list is empty by its type flexibility **preferred method** if (!myList.Any()) { // the list is empty } String Interpolation (Formatting a String) - Oftentimes, we need to format strings to display information in a more readable or structured manner. Here are some options: string name = "Himanshu"; int age = 25; // String formatting using concatenation Console.WriteLine("My name is " + name + ", and I am " + age + " years old."); // String formatting using composite formatting Console.WriteLine("My name is {0}, and I am {1} years old.", name, age); // String formatting using interpolation (C# 6.0+) Console.WriteLine($"My name is {name}, and I am {age} years old"); These are but a small example of the power and flexibility that C# and .NET bring to the table.Thank you for reading! We hope these C# .NET snippets will help you streamline your development process and boost your productivity.
Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment: if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3: Execute the APIs and test.