tags:

views:

224

answers:

4

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?

+8  A: 

In a utility class file.

ck
Yep. I would definitely put those in a static class.
Jon
Further, I usually do this in a class without a namespace
annakata
@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
+3  A: 

I'm assuming your referring to a String variable. If that's the case I would suggest one of two things

  1. 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
      }
    }
    
  2. 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
Like the idea of an extension method
Martijn
+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
+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
Is it possible to write an extension method for Request.Querystring["value"] ?
Martijn
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
@martijn: `TypeOf(Querystring["value"])==System.String` isn't it? so `MyStringExtensionsClass.ExtensionMethodName( this System.String theString, ... ) { ... }` would likely suffice
Kris
Thnx, Sorry I am not that good yet in C#.
Martijn