Neat default parameter trick.

EDIT:

I have a library I made with a lot of overloads for a few different methods, of which have default params in them. I needed an option to have the default params set across all the overloads for some cases, and did not want to make even another set of overloads for an already high amount.

You can do it like this:

 //Simplified example. // Null = true, else false. public bool? IsNeeded { get; set; } = false; // Has several overloads public T DoStuffExample<T>(int yourValue, bool isNeeded = true) { if (IsNeeded != null) isNeeded = false; } // Has several overloads. public T DoOtherStuffExample<T>(int yourValue, bool isNeeded = true) { if (IsNeeded != null) isNeeded = false; } 

by JacobKemple via /r/csharp

Leave a Reply