views:

218

answers:

4

Ok, i'm well and truly stumped here.

I've written extension methods before, and never had any problems. However, i've never had to use them in Console Apps. The following code won't compile and I have no idea why! I created a simple console app to try it out and it just won't work:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "hello";

            Console.WriteLine(s.TestMethod());

            Console.Read();
        }
    }

    public static class ExtensionTest
    {
        public static string TestMethod(this string input)
        {
            return input.ToUpper();
        }
    }
}

Can anyone see what's wrong here?

The first error i'm running into is "Type expected" on line 21, which is:

(this string input)

I know i could quite easily just change to:

Console.WriteLine(ExtensionTest.TestMethod(s));

But i'd really like to know why i can't write this extension method in a console app.

Thanks for any help!

+4  A: 

Just created a new Console application using that exact text and it compiled and worked as expected. Sure it's targeting the right framework?

Agent_9191
Same thing here... are you sure you typed exactly the code above ?
Cédric Rup
By the way : compiler complains about an undifined 'System.Runtime.CompilerServices.ExtensionAttribute' if V2 is targeted... and you can use extension methods if you define your own !
Cédric Rup
total school-boy! using vs2005, so it would be .net 2.0. Just gonna use a helper class seeing as I don't have access to vs2008!
seanxe
A: 

It seems, your project is set up to compile for v2.0 of .NET framework. Try switching to v3.5 in project properties and referencing System.Core assembly..

elder_george
If you are using the C# 3.0 compiler you can use extension methods with .Net 2.0. http://blogs.oberon.ch/tamberg/2009-02-06/implementing-linq-on-the-dotnet-mf.html (this is for the micro framework yet it works with the standard 2.0 as well)
Matthew Whited
Yes, but he won't see System.Core to have ExtensionAttribute.Of course, manual implementation will work. Thank you for this point.
elder_george
+2  A: 

You sure you are using C#3.0? The code doesn't have a problem in it.

If you are targeting .NET 2.0 with C# 3.0 you can still ue extension methods by defining the following type in your project:

namespace System.Runtime.CompilerServices
{
     [AttributeUsage(AttributeTargets.Method)]
     public class ExtensionAttribute : Attribute
     {
         public ExtensionAttribute() { }
     }
}
Maximilian Mayerl
A: 

Ensure your project targets .NET Framework v3.0 or higher and make sure System.Core is a referenced assembly in your project.

NathanE
System.Core is V3.5 only ;o)
Cédric Rup