extension-methods

Ambiguous call between two C# extension generic methods one where T:class and other where T:struct

Consider two extension methods: public static T MyExtension<T>(this T o) where T:class public static T MyExtension<T>(this T o) where T:struct And a class: class MyClass() { ... } Now call the extension method on a instance of the above class: var o = new MyClass(...); o.MyExtension(); //compiler error here.. o.MyExtension<MyClass...

My generic type converter smells bad, exceptions at runtime, object as catch all, boxing etc.

Firstly, I've asked this question elsewhere, but meta.stackoverflow.com seems to think that asking the same questions elsewhere is fine, so here goes. I'll update both if/when I get an answer. I'm doing a lot of conversion between simple types and I wanted to handle it as nicely as possible. What I thought would be nice would be to be a...

Is an Extension Method the only way to add a function to an Enum?

I have a Direction Enum: Public Enum Direction Left Right Top Bottom End Enum And Sometimes I need to get the inverse, so it seems nice to write: SomeDirection.Inverse() But I can't put a method on an enum! However, I can add an Extension Method (VS2008+) to it. In VB, Extension Methods must be inside Modules. I r...

c# DateTime Add Property without extension Method

I am writing a class library where i need to extend System.DateTime to have a property called VendorSpecificDay such that DateTime txnDate = DateTime.Today; VendorSpecificDayEnum vendorDay = txnDate.VendorSpecificDay; public enum VendorSpecificDayEnum { Monday, Tuesday, ShoppingDay, HolidayDay } I realize that this is a perfe...

Is it possible to rewrite this tricky extension method?

Is it possible to rewrite this extension method without the parameter? public static string PropertyName<T>(this T obj, Expression<Func<T>> property) { var memberExpression = property.Body as MemberExpression; if (memberExpression == null) throw new ArgumentException("Expression must be a MemberExpression.", "property");...

How do I create Extension Methods for string type in Asp.net MVC 2 ?

Hi I'm trying to reach this goal but as far as I am, I've got nothing. I wish to add some static method to string type, which would return new changed string. I've got: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; namespace TestProject.Models...