Posts

Showing posts with the label c#

What is extension method with example in c#

Image
An extension method in C# allows you to add methods to existing types without modifying their source code or inheriting from them. These methods appear as if they were part of the original type.  Here's an example of an extension method: *** csharp code using System; public static class StringExtensions {     // Extension method to reverse a string     public static string Reverse(this string input)     {         char[] charArray = input.ToCharArray();         Array.Reverse(charArray);         return new string(charArray);     } } class Program {     static void Main(string[] args)     {         string originalString = "hello";         string reversedString = originalString.Reverse(); // Calling the extension method         Console.WriteLine($"Original string: {originalString}"); // Output: Or...

What is hash table in c# and when we should use it

Image
In C#, a hash table is implemented using the `Hashtable` class or, more commonly, the `Dictionary<TKey, TValue>` class in the `System.Collections.Generic` namespace. Both are used for storing key-value pairs, but `Dictionary<TKey, TValue>` is more type-safe and generally preferred over `Hashtable`. ### When to use a hash table (Dictionary in C#): 1. Fast Retrieval: Hash tables provide fast retrieval of values based on their associated keys. This is particularly useful when you need quick access to data based on some identifier. 2. Unordered Collection: If the order of elements doesn't matter, and you need to store and retrieve data based on unique keys, a hash table is a good choice. 3. Associative Mapping: When you want to establish an association between keys and values, such as mapping usernames to user profiles or IDs to corresponding objects. 4. Efficient Search: Hash tables provide O(1) average time complexity for retrieval, making them efficient for s...

What is method overloading in c# with example.

Image
Method overloading in C# allows you to define multiple methods with the same name in the same class, but with different parameter lists. This enables you to use the same method name for different behaviors based on the input parameters. Here's a simple example: ```csharp code``` using System; class Calculator {     public int Add(int a, int b)     {         return a + b;     }     public double Add(double a, double b)     {         return a + b;     }     public string Add(string a, string b)     {         return a + b;     } } class Program {     static void Main()     {         Calculator calculator = new Calculator();         Console.WriteLine(calculator.Add(2, 3)); // Output: 5         Console.WriteLine(calculator.Add(2.5, 3.5)); ...

What is the difference between var and dynamic in c#

Image
  In C#, `var` and `dynamic` are both used for type inference, but they have different behaviors. var is used for implicitly typed local variables, where the type is determined at compile-time based on the assigned value. Once the type is inferred, it is fixed, and the variable behaves like a statically typed variable.

How does dictionary works in c#

Image
In C#, the `Dictionary<TKey, TValue>` class is used to implement a dictionary, which is essentially a type of hashtable. Here's a breakdown of how the `Dictionary<TKey, TValue>` works: 1. Key-Value Storage:    - A `Dictionary<TKey, TValue>` stores data in key-value pairs.    - Each key in the dictionary must be unique. 2. Hash Function:    - Internally, the dictionary uses a hash function to convert the key into an index in the underlying array.    - This enables quick retrieval of values based on their keys. 3. Array Storage:    - The dictionary maintains an internal array to store the key-value pairs.    - The index for each key is determined by the hash function. 4. Collision Handling:    - Like other hashtables, the `Dictionary` class must handle collisions, where multiple keys hash to the same index.    - It typically uses techniques like chaining (linked lists at each inde...

What is interface in c# explain with example

Image
In C#, an interface is a contract that defines a set of methods, properties, events, or indexers that a class must implement. It provides a way to achieve multiple inheritances and helps in achieving abstraction. Here's a simple example: // Define an interface named IShape public interface IShape {     double CalculateArea(); // Method signature, to be implemented by classes } // Implement the interface in a class public class Circle : IShape {     public double Radius { get; set; }     public Circle(double radius)     {         Radius = radius;     }     // Implement the method from the interface     public double CalculateArea()     {         return Math.PI * Radius * Radius;     } } // Another class implementing the same interface public class Rectangle : IShape {     public double Width { get; set; }     public double Heigh...

Explain abstract class in c# with example

Image
An abstract class in C# is a class that cannot be instantiated on its own and is meant to serve as a base or template for other classes. It may contain abstract (unimplemented) methods and properties that must be implemented by derived classes. Here's a simple example: ```csharp using System; // Define an abstract class abstract class Shape {     // Abstract method to calculate area (must be implemented by derived classes)     public abstract double CalculateArea();          // Regular method     public void Display()     {         Console.WriteLine("This is a shape.");     } } // Derived class 1: Circle class Circle : Shape {     public double Radius { get; set; }     public Circle(double radius)     {         Radius = radius;     }     public override double CalculateArea()     {       ...

What is valuetuple in c# with example

Image
In C#, a ValueTuple is a lightweight data structure introduced in C# 7.0 that allows you to create tuples with named or unnamed elements. ValueTuples are value types, which means they are structs rather than reference types (classes), making them more memory-efficient. Here's an example of using ValueTuples: ```csharp using System; class Program {     static void Main()     {         // Creating a ValueTuple with named elements         var person = (Name: "John", Age: 30);         // Accessing elements using names         Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");         // Creating a ValueTuple with unnamed elements         var point = (3, 4);         // Accessing elements using itemN notation         Console.WriteLine($"X: {point.Item1}, Y: {point.Item2}");     } } `...

What are the differences between ref and out keywords?

Image
In C#, both `ref` and `out` are used as keywords when passing parameters to methods, but they have different purposes: 1. `ref`:    - `ref` is used to pass a variable as a reference to the method. Any changes made to the parameter inside the method are reflected outside of the method.    - The variable passed with `ref` must be initialized before calling the method.    - It is used for both input and output parameters. Example: ```csharp public void ModifyWithRef(ref int x) {     x = x * 2; } int value = 5; ModifyWithRef(ref value); Console.WriteLine(value); // Outputs 10 ``` 2. `out`:    - `out` is used for output parameters. It indicates that the method is expected to assign a value to the parameter.    - Unlike `ref`, the variable passed with `out` doesn't need to be initialized before calling the method.    - The method must assign a value to the `out` parameter before it returns. Example: ```csharp pu...

What is managed code and unmanaged code in c# with example

Image
Managed code and unmanaged code are terms used in the context of C# and the .NET framework to describe how the code is executed and managed by the runtime environment. Here's an explanation and an example of each: 1. Managed Code:    - Managed code refers to code that is executed within the .NET Common Language Runtime (CLR) environment. The CLR provides various services such as memory management, type safety, and garbage collection.    - C# code is typically considered managed code because it is compiled into an intermediate language (IL) that is executed by the CLR.    Example of managed code in C#:    ```csharp    using System;    class Program    {        static void Main()        {            Console.WriteLine("This is managed code executed by the CLR.");        }    }    ``` 2. Unmanaged Code...

Garbage collection in C# with example

Image
Garbage collection in C# is the automatic process of managing memory by identifying and reclaiming objects that are no longer needed, freeing up memory for reuse. It helps prevent memory leaks and makes memory management more efficient. Here's a simple example: ```csharp class MyClass {     public int Data;          public MyClass(int value)     {         Data = value;     } } class Program {     static void Main()     {         MyClass obj1 = new MyClass(42); // Create an object         MyClass obj2 = new MyClass(84); // Create another object         // Now, let's assume we no longer need obj1         obj1 = null; // Set obj1 to null to indicate it's no longer referenced         // At this point, the garbage collector may identify obj1 as unreachable         // a...

What is common language runtime (clr)

Image
The Common Language Runtime (CLR) is a fundamental component of the Microsoft .NET framework. It is responsible for executing and managing .NET applications. Here are some key aspects of the CLR: 1. Execution Environment: The CLR provides a runtime environment for executing .NET applications. It compiles Intermediate Language (IL) code into native machine code during execution, optimizing it for the specific hardware it's running on. 2. Memory Management: CLR handles memory management tasks, including memory allocation and garbage collection. It automatically reclaims memory occupied by objects that are no longer in use, which helps prevent memory leaks. 3. Type Safety: CLR enforces type safety by ensuring that only valid operations are performed on objects and data types, reducing the likelihood of common programming errors. 4. Exception Handling: It provides a robust exception handling mechanism for handling and recovering from runtime errors in a structured way. 5. S...