As an example, I have an several extension methods for converting strings and objects into decimals and int32
public static decimal ToDecimal(this object o)
{
return Convert.ToString(o).ToDecimal();
}
public static decimal ToDecimal(this string s)
{
decimal d = decimal.TryParse(s, out d) ? d : 0;
return d;
}
public static Int32 ToInt32(this object o) { //etc }
But I want to prevent chaining like such:
myobject.ToDecimal().ToDecimal();
or even
myobject.ToDecimal().ToInt32();
If the programmer wants to convert the decimal to int32, then I want him to use Convert.ToInt32() which may just be more efficient since the Convert.ToString part is omitted, and also has more features.
How can I tell C# that only object can use the extension method and not decimal, int etc?
You can’t. This isn’t an extension method issue so much as a general method parameter issue – it will always be valid when the argument can be converted to the method parameter type.
I can think of a few grotty hack-arounds:
That would prevent you calling
ToDecimal().ToDecimal()asdecimalisn’t a class; it would also prevent you callingToDecimal().ToString().ToDecimal()asstringdoesn’t have a parameterless constructor.I would suggest that it’s not really an appropriate extension method though, to be honest. I would suggest taking more care over how your conversions are performed to start with, and only doing them in very appropriate situations. For example, your current extension method would allow you to convert between
doubleanddecimalinappropriately, which isn’t a good idea. Under what circumstances do you really want to do this? Which types are you trying to convert?