Found 2628 Articles for Csharp

What is difference between using if/else and switch-case in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:43:48

313 Views

Switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.The switch statement is often used as an alternative to an if-else construct if a single expression is tested against three or more conditions.Switch statement is quicker. The switch statement the average number of comparisons will be one regardless of how many different cases you have So lookup of an arbitrary case is O(1)Using Switch −Exampleclass Program{ public enum Fruits { Red, Green, Blue } public static void Main(){    Fruits c = (Fruits)(new Random()).Next(0, ... Read More

How to implement interface in anonymous class in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:39:59

2K+ Views

No, anonymous types cannot implement an interface. We need to create your own type.Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.You create anonymous types by using the new operator together with an object initializer.Exampleclass Program{    public static void Main(){       var v = new { Amount = 108, Message = "Test" };     ... Read More

How to write retry logic in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:38:37

1K+ Views

Retry logic is implemented whenever there is a failing operation. Implement retry logic only where the full context of a failing operation.It's important to log all connectivity failures that cause a retry so that underlying problems with the application, services, or resources can be identified.Exampleclass Program{    public static void Main(){       HttpClient client = new HttpClient();       dynamic res = null;       var retryAttempts = 3;       var delay = TimeSpan.FromSeconds(2);       RetryHelper.Retry(retryAttempts, delay, () =>{          res = client.GetAsync("https://example22.com/api/cycles/1");       });     ... Read More

What is the difference between Monitor and Lock in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:36:43

2K+ Views

Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor.Enter with try and finally.Lock is a shortcut and it's the option for the basic usage. If we need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Montior class is your option.Example for Lock −Exampleclass Program{ static object _lock = new object(); static int Total; public static void Main(){    AddOneHundredLock();    Console.ReadLine(); } public static void AddOneHundredLock(){    for (int i = 1; i

How to sort a list of complex types using Comparison delegate in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:32:43

421 Views

Overloads of the Sort() method in List class expects Comparison delegate to be passed as an argument.public void Sort(Comparison comparison)CompareTo returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance.The Int16.CompareTo() method in C# is used to compare this instance to a specified object or another Int16 instanceExampleclass Program{    public static void Main(){       Employee Employee1 = new Employee(){          ID = 101,          Name = "Mark",         ... Read More

How to make use of Join with LINQ and Lambda in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:30:09

9K+ Views

Inner join returns only those records or rows that match or exists in both the tables. We can also apply to join on multiple tables based on conditions as shown below. Make use of anonymous types if we need to apply to join on multiple conditions.In the below example we have written 2 ways that can be used to join in Linq Here the Department and the Employee are joinedExampleclass Program{    static void Main(string[] args){       var result =       Employee.GetAllEmployees().Join(Department.GetAllDepartments(),       e => e.DepartmentID,       d => d.ID, (employee, department) ... Read More

What is if/then directives for debug vs release in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:27:28

1K+ Views

In Visual Studio Debug mode and Release mode are different configurations for building your .Net project.Select the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe).To change the build configuration −From the Build menu, select Configuration Manager, then select Debug or Release. Or On the toolbar, choose either Debug or Release from the Solution Configurations list.The code which is written inside the #if debug will be executed only if the code is running inside the debug mode.If the code is running in the release ... Read More

How to get the Unix timestamp in C#

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:26:03

5K+ Views

A Unix timestamp is mainly used in Unix operating systems. But it is helpful for all operating systems because it represents the time of all time zones.Unix Timestamps represent the time in seconds. The Unix epoch started on 1st January 1970.So, Unix Timestamp is the number of seconds between a specific dateExampleto get the Unix Timestamp Using DateTime.Now.Subtract().TotalSeconds Methodclass Program{    static void Main(string[] args){       Int32 unixTimestamp = (Int32)(DateTime.Now.Subtract(new       DateTime(1970, 1, 1))).TotalSeconds;       Console.WriteLine("The Unix Timestamp is {0}", unixTimestamp);       Console.ReadLine();    } }Output1596837896Exampleto get the Unix Timestamp Using DateTimeOffset.Now.ToUnixTimeSeconds() ... Read More

How to force garbage collection in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:24:11

2K+ Views

Yes it is possible to force garbage collector in C# to run by calling Collect() methodThis is not considered a good practice because this might create a performance over head. Collect() Forces an immediate garbage collection of all generations.Collect(Int32)Forces an immediate garbage collection from generation 0 through a specified generation.Example Live Demousing System; class MyGCCollectClass{    private const int maxGarbage = 1000;    static void Main(){       // Put some objects in memory.       MyGCCollectClass.MakeSomeGarbage();       Console.WriteLine("Memory used before collection: {0:N0}",       GC.GetTotalMemory(false));       // Collect all generations of memory.   ... Read More

How to create an array with non-default repeated values in C#?

Nizamuddin Siddiqui
Updated on 19-Aug-2020 13:19:46

576 Views

We can create an array with non-default values using Enumerable.Repeat(). It repeated a collection with repeated elements in C#. Firstly, set which element you want to repeat and how many times.Example 1class Program{    static void Main(string[] args){       var values = Enumerable.Repeat(10, 5);       foreach (var item in values){          System.Console.WriteLine(item);       }       Console.ReadLine();    } }Output10 10 10 10 10Example 2class Program{    static void Main(string[] args){       int[] values = Enumerable.Repeat(10, 5).ToArray();       foreach (var item in values){          System.Console.WriteLine(item);       }       Console.ReadLine();    } }Output10 10 10 10 10

Advertisements