Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 2010 compiler error for base class extensions

I have a c# class providing some simple classes and some base class extensions such as this one..

public static Boolean ToBooleanOrDefault(this String s, Boolean Default)
{
    return ToBooleanOrDefault((Object)s, Default);
}


public static Boolean ToBooleanOrDefault(this Object o, Boolean Default)
{
    Boolean ReturnVal = Default;
    try
    {
        if (o != null)
        {
            switch (o.ToString().ToLower())
            {
                case "yes":
                case "true":
                case "ok":
                case "y":
                    ReturnVal = true;
                    break;
                case "no":
                case "false":
                case "n":
                    ReturnVal = false;
                    break;
                default:
                    ReturnVal = Boolean.Parse(o.ToString());
                    break;
            }
        }
    }
    catch
    {
    }
    return ReturnVal;
}

The class compiles fine and appears to have no issues. I have then referenced the project in a web project and VS2010 intellisense recognises the base class extensions and F12/got to definition jumps to the original source code as expected. However when I compile the web project I get an error for each usage of the base class extension...

Error   28  'string' does not contain a definition for 'ToBooleanOrDefault'

This looks to me like the reference is not used by the compiler so it ignores all my base class extensions. Ideas? The solution was migrated from VS2008 where all worked fine.

like image 898
Flapper Avatar asked Nov 06 '22 11:11

Flapper


2 Answers

Apart from for common mistakes (forgetting to include the extension class's namespace), you should make sure that both projects use the same .NET version. Sometimes a v4 project will not reference properly assemblies built for earlier versions of the framework

Gets me all the time

like image 193
Panagiotis Kanavos Avatar answered Nov 14 '22 22:11

Panagiotis Kanavos


After you migrated, a report was made, possibly with warnings of something that needed manual fixing. What you may try to do is remove the reference and wait until IntelliSense recognizes it (red lines under each use of the referenced classes). Then add the reference again, see if it compiles now.

Note that this is not about a base class, but about your extension methods not being found. You may also want to check the .NET version of the project (.NET 3.5 or higher support extension methods) and check the line that raises the error: make sure the using-statement is available.

like image 43
Abel Avatar answered Nov 14 '22 21:11

Abel