Here's the method I would like to add:
private string S(int i){
return i == 1 ? "": "s";
}
I would like it so I can use it in any part of the application. But where should I add this and how can I make it so it's accessible everywhere?
Here's the method I would like to add:
private string S(int i){
return i == 1 ? "": "s";
}
I would like it so I can use it in any part of the application. But where should I add this and how can I make it so it's accessible everywhere?
This, in fact, would be an int
extension method. It needs to be static
; also, in order for it to be accessible everywhere, it needs to be public
. Extension methods need to be defined in a static class
, and they should contain the keyword this
before the first argument, which would be indicating the type to extend. So the final approach would be:
namespace YourNameSpace
{
public static class Int32Extensions
{
public static string S(this int i)
{
return i == 1 ? "" : "s";
}
}
}
To use it somewhere else, you need to use the namespace in your subject code file
using YourNameSpace;
And simply call it
int i = 3;
string str = i.S(); //equals "s"
The method that you are showing is not an extension method. An extension method would (for instance) be this:
public static class MyStringExtensions
{
public static string S(this string text, int i)
{
return i == 1 ? "" : text;
}
}
The method has to be static, must be in a static class, and the first parameter must have the keyword this
before declaration.
Put the class into the base of your namespace, so that you will automatically be able to access it from anywhere without having to specify the namespace with using
.