Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Encoding not an enumeration?

Tags:

c#

enums

encoding

I'm trying to figure out a way to store the encoding of a file in a database to then be able to retrieve it back into it's original type (System.Text.Encoding). But i'm getting an error I don't understand.

As a test, I created this small program to reproduce the error:

using System;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            object o = Encoding.Unicode;
            Encoding enc = (Encoding) Enum.Parse(typeof(Encoding), o.ToString());
        }
    }
}

The exception I get in the Parse line says:

Type provided must be an Enum.
Parameter name: enumType

So, basically as far as I understand is telling me that typeof(Encoding) does not return an Enum type? Thanks in advance for any help provided.

like image 816
Fran Casadome Avatar asked May 04 '12 17:05

Fran Casadome


1 Answers

No, it is not an enum. It is a class with static properties. Something like this:

public class Encoding
{
    public static Encoding ASCII
    {
         get
         {
             //This is purely illustrative. It is not actually implemented like this
             return new ASCIIEncoding();
         }
    }
}

If you want to store the encoding in the database, store the code page:

int codePage = SomeEncoding.CodePage;

And use Encoding.GetEncoding(theCodePage) to get the encoding.

like image 99
vcsjones Avatar answered Sep 19 '22 10:09

vcsjones