Codementor Events

Ten C# Popular Tips (Part -1)

Published Feb 22, 2021
Ten C# Popular Tips  (Part -1)

I am writung this article to both beginner ans advanced developer to take alook inti the following features.

TIP 1. Avoid race condition with TryGetValue function

int result = new Int32();
int32 calculatedTotal = 0;

var firstDic= new Dictionary<string,int>();
firstDic.add("ten",10);
firstDic.add("twenty",20);
firstDic.add("thirty",30

Point is avoid race conditions when checking an item exits in a dictionaly.
**Don't write this code **

if (firstDic.contains("thirty"))
{
  // another thread could remove the item before this code run !
    result=firstDic["thirty"];
    // TODO : Code ...
    calculatedTotal = result * 20;
}

Use this Code instead
check the value, assigns to out parameter if it exists in dictionary

  if (firstDic.TryGetValue("twenty",out result))
  {
    calculatedTotal =result * 30;   
    	Console.WriteLine($"Result : {result}");
  }
  else 
  {
    Console.WriteLine("Key does not exists");
  }

TIP 2. Discard Feature

The underscore can serve as the discards placeholder
think of discard as temporary, dummy variabls that is intentionally unused in application code.
Discards are equivalent to unassigned variables.
they do not have a value.

Assign a value to discard

_ = 12+14;

var x= _ ;  // You can't do this 

Its Typically used for following scenario's
Available For :

  1. Calls to methods with out parameters
  2. Tuple and object De-construction
  3. Pattern matching with "is " and "switch"

Here i will discuss first two scenario with C# code by example.
1. Calls to methods with out parameters
2. Discard out Parameters.png

2. Tuple and object De-construction
3. Tuple and object De-construction.png

TIP 3. Be more functional with the conditional Operator

instead of using if else blocks everytime for conditioning,
Its better to use ternary operator.

4. Be more Functional with Operators.png

I hope these paractive will help you to increase your coding parataice and make you skills more efficient,
In the second part i will add more great example that will help you to write your code more cleaner.

If you like this article please Follow and leave comment if you have any doubt. or any questions.

Thank you guys for supporting me ! 😊

Discover and read more posts from Rizwan
get started