Here are my top basic 12 C# utility Tips & Tricks I usually use when programming daily:

My most used tips and tricks that I use daily when programming in C# and dotnet.

Here are my top basic 12 C# utility Tips & Tricks I usually use when programming daily:
Photo by Oskar Yildiz / Unsplash
  1. Null-Conditional Operator including chaining:
// Will be null if either `person` or `person.Spouse` are null
int? spouseAge = person?.Spouse?.Age;

You can also provide a fallback or default value:

var parent = person?.Parent?.FirstName ?? "N/A";

2. Printing of a variable, type or member without hard coding:

var myString = "String Contents";

3. Print the current method name dynamically:

using System;

public class AClass{
	public void Method1{
    	var currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;
        Console.WriteLine(currentMethod); // "Method1"

4. Use of Interpolated strings that can be useful for email templates

Console.WriteLine($@"Testing \n 1 2 {5 - 2}
New line");

Testing \n 1 2 3
New line

5. Join an array of characters to a single string:

string.Join("", array.ToArray());

6. Date formatting comes in super handy, here's a list of snippets from the book [1]:

var year = String.Format("{0:y yy yyy yyyy}", dt); // "16 16 2016 2016" year
var month = String.Format("{0:M MM MMM MMMM}", dt); // "8 08 Aug August" month
var day = String.Format("{0:d dd ddd dddd}", dt); // "1 01 Mon Monday" day
var hour = String.Format("{0:h hh H HH}", dt); // "6 06 18 18" hour 12/24
var minute = String.Format("{0:m mm}", dt); // "50 50" minute
var secound = String.Format("{0:s ss}", dt); // "23 23" second
var fraction = String.Format("{0:f ff fff ffff}", dt); // "2 23 230 2300" sec.fraction
var fraction2 = String.Format("{0:F FF FFF FFFF}", dt); // "2 23 23 23" without zeroes
var period = String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
var zone = String.Format("{0:z zz zzz}", dt); // "+0 +00 +00:00" time zone

7. Copying arrays - both shallow and deep:

var sourceArray = new int[] { 11, 12, 7 };
var destinationArray = (int)sourceArray.Clone();
//destinationArray will be created and will have 11,12,17.

// deep copy
A[] array2 = array1.Select (a =>(A)a.Clone()).ToArray();

8. Get all members values of an enum:

enum MyEnum
foreach(MyEnum e in Enum.GetValues(typeof(MyEnum)))
// Will print    

Enum equality check:


9. Convert a List to a HashSet:

Checking if an element is present in a HashSet is faster than in a List (0(1) vs 0(n)) esp. with large data sets.

var hashSet = new HashSet<YourType>(yourList);

10. Use of Singleton constructor pattern:

Singleton can be useful when managing access to a resource that is shared across the application and might be costly to have multiple e.g. database connection pool.

public class Singleton
    public static Singleton Instance { get; } = new Singleton();
    private Singleton()
    // Put custom constructor code here

11. Simple Object initializers with non-default constructor:

Instead of creating a new class and assigning the properties individually, you can use an initializer.

public class Article {
	public string Title { get; set; }
	public string Body {get; set; }
    public Article(int number)
    	// do stuff here

var newArticle = new Article(1) { Title = "Article 1", Body = "This is article 1 body" }

12. Named Arguments:

With such arguments, the order you pass them is not essential.

public static string JoinSomething(string left, string right)
	return string.Join("_", left, right);

Console.WriteLine(JoinSomething("left", "right")); // left_right
Console.WriteLine(JoinSomething(right: "right", left: "left")); //left_right

Another popular concept is the use of Extension Methods, which enable you to extend the behaviour of existing classes without modifying the source code or requiring special permissions.  


[1] - CSharpNotesForProfessionals

Deep Copy with Array
Why doesn’t ICloneable’s Clone method return a deep copy?Here is some sample code:class A : ICloneable { public int x = 2; public A(int x) { this.x = x; } pub...
how to compare string with enum in C#
string strName = “John”;public enum Name { John,Peter } private void DoSomething(string myname){case1: if(myname.Equals(Name.John) //returns false { } case2: if(myname == ...
How to convert List<T> to HashSet<T> in C#?
I have a List that has duplicates of objects. To solve that, I need to convert the List into a HashSet (in C#). Does anyone know how?
Extension Method in C# - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.