Extension Methods in . NET does not work

Asked

Viewed 100 times

1

I’m trying to create a Extension Methods for the class string. He’s not showing up.

My class with the extension method:

namespace MEUPROJETO.Extension
{
    public static class StringExtension
    {
        public static string PrimeiraLetraDeCadaPalavraMiuscula(this string frase)
        {
            frase = frase.ToLower();

            System.Globalization.CultureInfo cultureinfo = System.Threading.Thread.CurrentThread.CurrentCulture;

            return cultureinfo.TextInfo.ToTitleCase(frase);

        }
    }
}

Class where I try to use it:

namespace MEUPROJETO.Teste
{
   public static class TesteExt
   {
       public static void teste( )
       {
         string catdescription = "TESTANDO a frase nessa STRING.";

         catdescription = catdescription.PrimeiraLetraDeCadaPalavraMiuscula();
       }
   }
}

He can’t even compile, says the method doesn’t exist, like I do for him to appear?

The namespace influences?

  • 1

    You must specify the namespace where the Extension Method is declared: using MEUPROJETO.Extension

  • Thank you! Put as answer I mark you!

2 answers

2


I am putting the answer that the ramaral put in the comments, when he create his answer here I mark his as correct answer.

The solution is to add the namespace using MEUPROJETO.Extension where I want to use the methods.

-2

You didn’t mark the method PrimeiraLetraDeCadaPalavraMiuscula as an extension, add the following attribute to the variable declaration:

    [Runtime.CompilerServices.Extension()]
    public static String PrimeiraLetraDeCadaPalavraMiuscula(this string frase) //não precisa do this
    {
        frase = frase.ToLower();
        Globalization.CultureInfo cultureinfo = Threading.Thread.CurrentThread.CurrentCulture;

        return cultureinfo.TextInfo.ToTitleCase(frase).ToString;

    }
  • The PO declared the method correctly, The first parameter of an extension must be marked with keyword this. The compiler then generates the attribute Extension - this attribute should not be used directly by the programmer.

  • MSDN: "In C#, you do not need to use this attribute; you should use the this (C# Reference) Modifier for the first Parameter to create an Extension method. The Compiler Automatically emits Extensionattribute for Extension methods."

  • Ah, sorry. I’m not a C# X programmer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.