General functions

E

Eric Kiernan

In one of my classes, I have a function called
stripString( string myStr, char toRemove ) which strips a specified
character from a string i pass it. ie, i format some text number as
currency, but then strip the $ sign from the text field. My problem is
that I need this function in more than one class. I know I could (1)
copy the function into the second class, or (2) create a static class
called general, and then call general.stripString(), but is there any
way to just have a function file, filled with public functions, and no
class, so that I could just call stripString()?
 
P

Peter Duniho

In one of my classes, I have a function called
stripString( string myStr, char toRemove ) which strips a specified
character from a string i pass it. ie, i format some text number as
currency, but then strip the $ sign from the text field. My problem is
that I need this function in more than one class. I know I could (1)
copy the function into the second class, or (2) create a static class
called general, and then call general.stripString(), but is there any
way to just have a function file, filled with public functions, and no
class, so that I could just call stripString()?

For your specific example, you don't need your own method. The String
class already has the Replace() method, which can accomplish exactly the
same thing:

string str = "The quick brown fox jumped over the lazy dog";

str = str.Replace("o", "");
// str now is "The quick brwn fx jumped ver the lazy dg"

As for the more general question, no...all methods and variables have to
be contained in a class or struct. You will always have to specify a type
name or instance variable to call a method.

The use of extension methods can simplify the call site. For example, had
there been a need to actually write a "stringString()" method, you could
do it like this:

static class MyExtensions
{
public static string stripString(this string str, char toRemove)
{
return str.Replace(toRemove, "");
}
}

Then you'd be able to call the method like this:

string str = "The quick brown fox jumped over the lazy dog";

str = str.stripString('o');

Hope that helps.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top