Reputation: 4453
I know I can extend the string class like so:
public static class EMClass
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}
public static int ToInt32Static(string s)
{
return Int32.Parse(s);
}
}
And use it like this:
string x = "12";
x.ToInt32Ext()
But how can I make it to where I can use it like this:
int x = string.ToInt32("15");
Upvotes: 4
Views: 2115
Reputation: 28735
Personally, I don't see a lot of use for an extension-method wrapper to a method call that's already a short one-liner. On the other hand, wrapping the Int32.TryParse pattern to return a nullable int can be pretty convenient:
public static int? ToInt32(this string input)
{
if (String.IsNullOrEmpty(input))
return null;
int parsed;
if (Int32.TryParse(input, out parsed))
return parsed;
return null;
}
This allows you to parse a value that might not be present, or might not contain an integer, and provide a default value in a single line of code:
int id = Request.QueryString["id"].ToInt32() ?? 0;
Upvotes: 0
Reputation: 6308
You can't really do this... the closest you are going to get is this:
public static class Ext
{
public static class String
{
public static int ToInt32(string val)
{
return Int32.Parse(val);
}
}
}
//Then call:
Ext.String.ToInt32("32");
Which i'm surprised the compiler even allows you to name a class "String"
Just for entertainment, i thought of another fun way to do it, though i would never recommend this. Add:
using String = NameSpace1.Ext.String;
//Then you can access it as:
String.ToInt32("32"); //Yipes
Upvotes: 1
Reputation: 532435
Extension methods only apply to instances of a class, not the class itself. You can't extend a class with a class method using an extension. Note that you should easily be able to do what you want with an extension method, just using.
var fifteen = "15".ToInt32Ext();
Upvotes: 1
Reputation: 17281
What I did in our project at work is created a class called Strings which is where I put all of our extension methods. That way you have something that visually looks similar to string.
You can call the extension method in your example like so too (not all people might like this, but I use this myself depending on the code I'm working on):
int x = "15".ToInt32();
Upvotes: 3