Why can’t I call an extension method from a base class of the extended type‏?

Consider this situation: public class Base { public void BaseMethod() { } } public class Sub : Base { public void SubMethod() { } } public static class Extensions { public static void ExtensionMethod(this Base @base) { } } Here are some interesting assertions about this code: I cannot call the extension method using ExtensionMethod() … Read more

Anonymous Types – Are there any distingushing characteristics?

EDIT: The list below applies to C# anonymous types. VB.NET has different rules – in particular, it can generate mutable anonymous types (and does by default). Jared has pointed out in the comment that the naming style is different, too. Basically this is all pretty fragile… You can’t identify it in a generic constraint, but: … Read more

Convert string to nullable type (int, double, etc…)

Another thing to keep in mind is that the string itself might be null. public static Nullable<T> ToNullable<T>(this string s) where T: struct { Nullable<T> result = new Nullable<T>(); try { if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) { TypeConverter conv = TypeDescriptor.GetConverter(typeof(T)); result = (T)conv.ConvertFrom(s); } } catch { } return result; }

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