Collection of Userful C# Extension methods

I know that extension methods get a bad reputation because many people have a tendency to abuse them and stick any function they can in them. I've been guilty of it from time to time. But I thought maybe we could share our favorite methods that make our code more legible and provide more functionality to the language.

I'll go first:

public static class StringExtensions { public static string OnlyDigits(this string value) { return new string(value?.Where(c => char.IsDigit(c)).ToArray()); } } var ssn = "123-12-1234"; ssn = ssn.OnlyDigits(); // "123121234" 

I just think this way is immediately obvious whats going on. You could have just done:

var ssn = "123-12-1234"; ssn = new string(ssn?.Where(c => char.IsDigit(c)).ToArray()); // "123121234" public static class ObjectExtensions { public static T DeepCopy<T>(this T a) { return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(a)); } } //cloning a work schedule for a new week var oldSchedule = GetSchedule(DateTime oldWeek); var newSchedule = oldSchedule.DeepCopy(); newSchedule .Week = newWeek; 

I needed a Deep Copy in a few places and instead of sprinkling that JsonConvert line everywhere I went with the extension. If you were to just glance at it you'd know what is going on right away. Otherwise it would have looked like:

var oldSchedule = GetSchedule(DateTime oldWeek); var newSchedule = JsonConvert.DeserializeObject<Schedule>(JsonConvert.SerializeObject(oldSchedule)); newSchedule .Week = newWeek; 

For things I use often I find this really helps. But if I only need something once I'd probably just leave it in the original method to keep the extension clutter down.

Anyone else got nifty ones they want to share?

by SoiledShip via /r/csharp

Leave a Reply