In my application I have a method to check a variable is a number or not. This method is called more than once in my code. The method is called from the codebehind pages. Like this method I have more methods which i cannot place within a single class (like Staff). Where should I put this kind of methods?
Yep. I would definitely put those in a static class.
Jon
2009-05-28 11:40:37
Further, I usually do this in a class without a namespace
annakata
2009-05-28 11:45:49
@annakata The problem with not putting a name space is later on you get a lot of "Common" logic which then gets a bit messy.
Saint Gerbil
2009-05-28 12:06:23
+3
A:
I'm assuming your referring to a String variable. If that's the case I would suggest one of two things
If you're using PRE .NET 3.0 you could put it in a StringHelper class like so:
public static class StringHelper { public static bool StringIsNumber(String value) { //do your test here } }
If you're using POST .NET 3.0 you could refactor them as extension methods and do something like this
public static class StringExtensions { public bool IsNumber(this String value) { //do your test here } }
Joseph
2009-05-28 11:42:25
+1
A:
Sounds like you might be able to use the built-in functions int.TryParse(string, out int)
or double.TryParse(string, out double)
which both return a bool, but in any case go for ck's suggestion.
mdresser
2009-05-28 11:42:42
+4
A:
In C# 3.0, I would probably make this an extension method on the string class. I would group all of my string extensions into a single static class to improve readability.
public static class StringExtensions
{
public static bool IsNumeric( this string source )
{
if (string.IsNullOrEmpty( source ))
{
return false;
}
...
}
public static bool IsMoney( this string source )
{
...
}
...
}
Usage:
if (amountLabel.Text.IsNumeric())
{
...
}
tvanfosson
2009-05-28 11:43:50
Is it possible to write an extension method for Request.Querystring["value"] ?
Martijn
2009-05-28 11:56:22
Since the Item property of a NameValueCollection is a string, this extension method should work on it. If you wanted to have something like Request.QueryString.IsNumeric("value"), then you'd need to make "this" of type NameValueCollection and rewrite the method accordingly.
tvanfosson
2009-05-28 12:01:25
@martijn: `TypeOf(Querystring["value"])==System.String` isn't it? so `MyStringExtensionsClass.ExtensionMethodName( this System.String theString, ... ) { ... }` would likely suffice
Kris
2009-05-28 12:03:45