Showing posts with label C# Cool Code Tips. Show all posts
Showing posts with label C# Cool Code Tips. Show all posts

Tuesday, May 21, 2024

Magic windows GodMode mindblowing cool stuff

Create a folder anywhere in Windows Desktop
Rename the folder with GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} 

and open and see the magic.

Share your reaction in the comment section.

Wednesday, July 20, 2022

C# Expression bodied Method reduce lines of code

C#: String.IsNullOrEmpty vs String.IsNullOrWhiteSpace

C#: String.IsNullOrEmpty vs String.IsNullOrWhiteSpace

Monday, August 16, 2021

Hello world Csharp

Next time you write Hello World! Do this,

using static System.Console;
public class Program {
static void main() => WriteLine("Hello World");
}

 

Saturday, June 5, 2021

Clean Code Exception Filters in c#

 

Clean code always looks like it was written by someone who cares.”
― Robert C. Martin, Uncle Bob

C# Exception filters has been around since advent of C# 6.0 , I'm sure we rarely use it because we are so used to old way of using conditional exception handling.

Cut to the chase........!

Run dotnet in browser
https://try.dot.net/
No alt text provided for this image
No alt text provided for this image

Happy Coding!


Thursday, July 16, 2020

C# int.Parse() vs int.TryParse()


image

image



















Let’s try to understand with a simple example as shown in below.

image

In this case the string val, would be converted into integer without any error or exception; and that is what is intended with int.Parse() method.

The int.Prase() method throws three different types of exceptions depends on the data provided.

  • If parameter value is null, then it will throw ArgumentNullException
  • If parameter value is other than integer value or not in proper format, it will throw FormatException.
  • if parameter value is out of integer ranges, then it will throw  OverflowException.

 

Incase of  int.TryParse() method, when it converts the string representation of an number to an integer;  it set the the out variable with the result integer and returns true if successfully parsed, otherwise false.

image

Keep in mind in case of int.TryParse(), in case there won’t be any exception. Either it is for null parameter, incorrect format or out of value integer. Everytime, the result value would be set to 0 and method would return false.

 

image

 

Thursday, April 23, 2020

C# Operators Null-coalescing ,Null-conditional and Chaining


C# Local Function use only just once

c# Array SequenceEqual() and Reverse()

C# Collection by its capability, use it wisely


Best Practice C# Make use of AS operator for casting object

Remember to use As operator, here is the simple reason to avoid unnecessary exception is thrown.

With exception


Student s= new Student();
Object o = s;

var newStudent=  (string)o;// Exception casting not possible

As Operator to rescue, AS operator returns null if not compatible else right conversion object type

Student s= new Student();
Object o = s;

var newStudent=  o as string;// Exception casting not possible




Tuesday, April 21, 2020

Join and Set based operation using IEnumerable

Zip method of List is very interesting and very helpful out of box intersect functions where handy . It ignores the non mapping item from two collection list.

ReadOnly vs Immutable collection


ReadOnly Gotcha's

If we declared a collection readonly then it is just a wrapper around the source collection. Here is a catch when I say readOnly collection is just a wrapper I mean it refer source as a reference. There is a point when external library refer readonly collection at a given instance it holds say 10 values. Later stage in the code base if the source reference collection is updated with 11 values in it and we don't want the external library to consume that , in such case readOnly library introduces a complication. For our rescue we should use Immutable only when we are certain readOnly refers to a source that can change due to some conditional logic.

External Library- Refer ReadOnly -R


  • R- refer source collection S holds 10 values
  • S- Later in the code we add 11 values which External library shouldn't refer to..
  • R- refer source collection S holds 11 values





Efficient Use of Dictionary using custom data type


 Note
The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.



Monday, April 20, 2020

Performance List.Remove(T) Method is an O(n) operation

List.Remove(T) Method

If type T implements the IEquatable generic interface, the equality comparer is the Equals method of that interface; otherwise, the default equality comparer is Object.Equals.
This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

Performance List.Item[Int32] Property is O(1) operation

List.Item[i] is O(1) operation

Reason : There is a very large data list and suppose system wants to lookup for 9999 some element in the list. The operation performed to located is one step that is current location+ 9999= 0+9999

Gets or sets the element at the specified index.
C#
public T this[int index] { get; set; }
List accepts null as a valid value for reference types and allows duplicate elements.
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index].
Retrieving the value of this property is an O(1) operation; setting the property is also an O(1) operation.

Sunday, April 19, 2020

C# Short circuiting vs Non Short Circuiting logical condition

Short Circuit use && just check first condition and decide the outcome whereas & will evaluate all and conditions. Non short circuit may increase cyclomatic complexity.

How to Use Keywords as Variable Names @csharp

Use Keywords as Variable Names in #csharp var @string= string.Empty;
@string = "We can use keyword string as variable name, cool huh! trick compiler, we know better.."
In case, if you want to use Keywords as variable names (identifiers), then you need to include @ as a prefix for your variable names. For example, @switch is a valid identifier but the switch is not because it's a keyword and having a special meaning for the compiler.

Tuesday, August 6, 2019

C# Null Object Design pattern

public Customer GetByPhoneNumber(string phoneNumber)
{
  return _customerRepository
         .List(c => c.PhoneNumber == phoneNumber)
         .FirstOrDefault();
}

Problem with null


var customer = GetByPhoneNumber(phone);
 //Why null check this break design principle 
int orderCount = customer != null ? customer.OrderCount : 0;
decimal totalPurchase = customer != null ? customer.TotalPurchase : 0m;

Create NotFound Object Property



public class Customer
{
  public static Customer NotFound = 
     new Customer() { OrderCount=0, TotalSales=0m };
 
  // other properties and behavior
}

Final outcome No Null checks required


var customer = GetByPhoneNumber(phone);
int orderCount =  customer.OrderCount ;
decimal totalPurchase =customer.TotalPurchase;