I needed a one-liner to convert a string to an integer, and if the string is anything invalid, then just set it to zero. So I made the following extension method, but I can imagine there is a system method to do this in one line.
Is there another way to do this in one line without creating an extension method?
using System;
namespace TestForceInteger
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("testing".ForceInteger() + 1);
Console.WriteLine("199".ForceInteger() + 1);
int test = StringHelpers.ForceInteger(null);
Console.WriteLine(test + 1);
Console.ReadLine();
//output:
//1
//200
//1
}
}
public static class StringHelpers
{
public static int ForceInteger(this string potentialInteger)
{
int result;
if (int.TryParse(potentialInteger, out result))
return result;
else
return 0;
}
}
}
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
So the first parameter must be int preceded with the this modifier. For example, the IsGreaterThan() method operates on int, so the first parameter would be, this int i . Now, you can include the ExtensionMethods namespace wherever you want to use this extension method.
An extension method is "a public static method in a static class" and can still be used as such. It just has the additional syntactic sugar of being callable with a different syntax.
What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.
Not as a one-liner, afaik, but if you want to avoid the extension method you can initialize the result to 0 and ignore the outcome of TryParse
:
int result = 0;
int.TryParse(potentialInteger, out result)
Not a conventional way with the framework libraries, no.
Your extension method would be better if it returned a nullable int, so that you could distinguish between "invalid" and 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With