views:

117

answers:

2

I've written a simple extension method for a web project, it sits in a class file called StringExtensions.cs which contains the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Useful extensions for string
/// </summary>
static class StringExtensions
{
    /// <summary>
    /// Is string empty
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsEmpty(this string value)
    {
        return value.Trim().Length == 0;
    }
}

I can access this extension method from all the classes I have within the App_Code directory. However I have a web page called JSON.aspx that contains a series of [WebMethods] - within these I cannot see the extension method - I must be missing something very obvious!

+4  A: 

In order to see the extension method you must have an using directive for the namespace in which the class containing the extension method is declared.

Fredrik Mörk
@Jon: thanks; the using *statement* is a quite different thing.
Fredrik Mörk
@Fredrik: No problem - it's a very easy mistake to make. If it's any consolation, I got it wrong throughout the first draft of the first chapter of C# in Depth. I was mortally embarrassed when Eric pointed it out, given my normal pedantry around terminology.
Jon Skeet
@Jon: Currently the file containing the extension method has no namespace. I've added one (namespace Dog{}), then adding this to the JSON.aspx file (<%@ Import Namespace="Dog" %>) but it still doesn't make any difference
Peter Bridger
@Peter: Does the method work if you call it explicitly as StringExtensions.IsEmpty(text)?
Jon Skeet
@Jon: That gave "'StringExtensions' is inaccessible due to its protection level" - so I've changed the StringExtensions.cs file code from "static class StringExtensions" to "public static class StringExtensions" and that's solved it - D'oh! :)
Peter Bridger
+1  A: 

StringExtensions.cs file needed to have the class declared as public

Previously:

static class StringExtensions{ ... } 

Fixed:

public static class StringExtensions{ ... } 
Peter Bridger