How to restrict the extension?

Good morning.
There is an extension to all data types
public static Int32 ToInt32(this Object line)
{
 return Convert.ToInt32(line);
}


But I would like to appear on the on the similarity of types String, Int, Double, etc., is how to do?
July 12th 19 at 17:07
2 answers
July 12th 19 at 17:09
It do not work, unfortunately.
I propose to make a few similar methods in the same class, one for each desired type:
public class NumericExtensions
{
 public static Int32 ToInt32(this Double line)
{
 return (Int32)line;
}
 public static Int32 ToInt32(this float line)
{
 return (Int32)line;
}
 public static Int32 ToInt32(this String line)
{
 var res;
 int.TryParse(line, out res);
 return res;
}
 // ... for each desired type
}
I learned early on, they just come out very much :( - marcos.Moscis commented on July 12th 19 at 17:12
: why so many? Just a lot of just 14 pieces. Or use as you wrote with the Object. But I'd left a few different. Or I would have done without the extension, but just a regular static class (as you suggested, or multiple methods).
public static class NumericHelper
{
 public static Int32 ToInt32(this Object line)
{
 return Convert.ToInt32(line);
}
}
int x = NumericHelper.ToInt32(myvar);

After all, why limit the extension? To space not podskazala this method. Here and never will. I don't like too many unnecessary methods. - Rodger commented on July 12th 19 at 17:15
July 12th 19 at 17:11
You extend the base object, not to do. Only by creating different methods for the object

Find more questions by tags C#