Problems using "using" to access static methods

Asked

Viewed 36 times

0

I created in C# a static class with the methods Decode() and Encode() as in the code below:

namespace Crypt {
    public static class CaesarCipher {
        public static string Decode(string text, byte key) {
            // Meu código...
        }
        public static string Encode(string text, byte key) {
            // Meu código...
        }
    }
}

In my main code - archive Program.cs - I am trying to simplify the calling of these methods using the Directive using.

On my first attempt, I tried to create an alias as follows:

using Decode = Crypt.CaesarCipher.Decode;
using Encode = Crypt.CaesarCipher.Encode;

The problem is that the compiler generates the following error:

Program.cs(29,26): error CS1001: Identificador esperado

Reading the documentation, I discovered about the use of using static, which serves precisely to access the static members of a type without needing to qualify access with the name of the same. I tried to apply it to my code that way:

using static Crypt.CaesarCipher.Decode;
using static Crypt.CaesarCipher.Encode;

However, the compiler again generated an error:

Program.cs(29,19): error CS0106: O modificador "static" não é válido para este item

What I’m doing wrong?

1 answer

3


You must statically import the class and not the method:

using static Crypt.CaesarCipher;

public class Program {
    public static void Main() => Decode("", 0);
}

namespace Crypt {
    public static class CaesarCipher {
        public static string Decode(string text, byte key) => "";
        public static string Encode(string text, byte key) => "";
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

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