In C#, what happens when you call an extension method on a null object?

That will work fine (no exception). Extension methods don’t use virtual calls (i.e. it uses the “call” il instruction, not “callvirt”) so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases: public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } public … Read more

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

public static bool In<T>(this T source, params T[] list) { if(null==source) throw new ArgumentNullException(“source”); return list.Contains(source); } Allows me to replace: if(reallyLongIntegerVariableName == 1 || reallyLongIntegerVariableName == 6 || reallyLongIntegerVariableName == 9 || reallyLongIntegerVariableName == 11) { // do something…. } and if(reallyLongStringVariableName == “string1” || reallyLongStringVariableName == “string2” || reallyLongStringVariableName == “string3”) { // … Read more

Can I add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don’t need an extension method since you can just add the method directly. public static class ConfigurationManagerWrapper { public static ConfigurationSection GetSection( string name ) { return … Read more

Which method performs better: .Any() vs .Count() > 0?

If you are starting with something that has a .Length or .Count (such as ICollection<T>, IList<T>, List<T>, etc) – then this will be the fastest option, since it doesn’t need to go through the GetEnumerator()/MoveNext()/Dispose() sequence required by Any() to check for a non-empty IEnumerable<T> sequence. For just IEnumerable<T>, then Any() will generally be quicker, … Read more