Why does Property Set throw StackOverflow exception?

It’s because you’re recursively calling the property – in the set you are setting the property again, which continues ad infinitum until you blow the stack. You need a private backing field to hold the value, e.g. private string firstName; public string FirstName { get { return this.firstName; } set { this.firstName = value; } … Read more

Finding the variable name passed to a function

I know this post is really old, but since there is now a way in .Net 6 I thought I would share so others know. You can now use CallerArgumentExpressionAttribute as shown /// <summary> /// Will throw argument exception if string IsNullOrEmpty returns true /// </summary> /// <param name=”str”></param> /// <param name=”str_name”></param> /// <exception cref=”ArgumentException”></exception> … Read more

Create batches in linq

An Enumerable.Chunk() extension method was added to .NET 6.0. Example: var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 }; var chunks = list.Chunk(3); // returns { { 1, 2, 3 }, { 4, 5, 6 }, { 7 } } For those who cannot upgrade, the source is available on … Read more

How to read a text file reversely with iterator in C#

Very fast solution for huge files: From C#, use PowerShell’s Get-Content with the Tail parameter. using System.Management.Automation; using (PowerShell powerShell = PowerShell.Create()) { string lastLine = powerShell.AddCommand(“Get-Content”) .AddParameter(“Path”, @”c:\a.txt”) .AddParameter(“Tail”, 1) .Invoke().FirstOrDefault()?.ToString(); } Required reference: ‘System.Management.Automation.dll’ – may be somewhere like ‘C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0’ Using PowerShell incurs a small overhead but is worth it … Read more

Regex for numbers only

Use the beginning and end anchors. Regex regex = new Regex(@”^\d$”); Use “^\d+$” if you need to match more than one digit. Note that “\d” will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use “^[0-9]+$” to restrict matches to just the Arabic numerals 0 – 9. If you need to … Read more