I try to create a string extension with the method Space(int) in it. If I have an instance of a string, then its no problem. But without I have no Idea.
The call should be: string.Space(2)
or String.Space(2)
Not "".Space(2)
!!!
In this example, the method should return 2 space characters (" "
).
Anybody to help?
CodePudding user response:
An extension method is supposed to act on an object instance, that's how and why it has the syntax it got.
But in your case, your method does not act on a string instance, so what's the point of trying to define it as a string extension method? Just keep it an old boring static method. There's nothing wrong with ye'ole static methods...
CodePudding user response:
Thank you Sweeper:
namespace Exp.Util.Extension
{
public static class IntegerExtension
{
public static string ToSpaces(this int aData)
{
return new string(' ', aData);
}
}
}
CodePudding user response:
For this concrete example I think you can simply work with the string constructor:
var spaces = new string(' ', 2);