tags:

views:

68

answers:

2

I'm reading this code sample:

And since I don't know C#, I decided to give it a go.

While compiling I've got this message:

Main.cs(32,65): error CS1061: Type `string' does not contain a definition for `Base64ToHex' and no extension method `Base64ToHex' of type `string' could be found (are you missing a using directive or an assembly reference?)
Compilation failed: 1 error(s), 0 warnings

I've look in MSDN and as expected I didn't find a reference for that method.

Question: Where did that method came from?

p.s. My code looks like:

using System.Security.Cryptography;
using System.Text;
using System;

class MainClass
{ 
    public static string Encrypt(string toEncrypt, string key, bool useHashing)
    {
         ..... // same as in post
         .....
    }

    public static void Main( string [] args )
    {
        string key = "secret";

        Console.WriteLine( Encrypt("oscar" + "000", key, true ).Base64ToHex() );
    }

}

+1  A: 

If that code ever complied, Jeff probably had an extension method on String called "Base64ToHex". Extension methods allow you to define methods to "extend" other classes, such that it appears that the method was actually defined in that class:

public static class ExtensionMethods
{
    public static string Base64ToHex(this string str)
    {
     return ...;
    }
}
Michael Petrotta
This is more likely. I didn't knew about extensions methods. They could be added only to non-final classes I guess, and I guess string is non final, am I right? What's with the "static" access modifier ? Is it needed? What does an static class means?
OscarRyz
The String class is sealed (The "final" access modifier is Java. Same thing.). That's what's nice about extension methods - they allow you to extend "non-extendable" classes. The method must be static, but the class need not be. A static class is one that cannot be instantiated (so that you aren't tempted to do it, accidentally).
Michael Petrotta
To amplify, you can declare an extension method anywhere you like, as long as you reference the containing class (with a using statement) when you call the method. I like to group my extension methods (I don't have a lot of them) by function, and not just put them willy-nilly.
Michael Petrotta
+1  A: 

There is no Base64ToHex method in System.String. I think you're looking for Convert.FromBase64String and BitConverter.ToString:

string encrypted = Encrypt("oscar" + "000", key, true);
Console.WriteLine(BitConverter.ToString(Convert.FromBase64String(encrypted)));


I took a look at your link, and I'm guessing he wrote a helper extension method that does the same:

public static string Base64ToHex(this string s)
{
    return BitConverter.ToString(Convert.FromBase64String(s));
}
lc