Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding constructor (or function) to enum

Tags:

c#

enums

I am not sure if a constructor is exactly what I am looking for but if I explain what I am trying to do hopefully someone can tell me if I am trying to do is a silly idea or whether there are ways to do it.

So I have an enum:

public enum MessageType
{
    Normal, 
    Error, 
    Chat, 
    Groupchat, 
    Headline
}

This enum is basically a wrapper for the jabber.net MessageType. So I want to create my enum from this. So at the moment I have a function like this:

private MessageType ConvertMessageType(JabberMessageType jabberType)
{
    MessageType type = MessageType.Error;

    switch (jabberType)
    {
        case JabberMessageType.normal:
            type = MessageType.Normal;
            break;

        //etc
    }

    return type;
}

So I have to use enum MessageType type = ConvertMessageType(JabberMessageType.groupchat);

What I would like though is to be able to do something like:

enum MessageType type = MessageType(JabberMessageType.groupchat);
// or 
enum MessageType type = MessageType.FromJabberJid(JabberMessageType.groupchat);

So that the conversion belongs with the enum rather than being a method outtside of.

like image 566
Firedragon Avatar asked Nov 10 '11 12:11

Firedragon


People also ask

Do enums need constructors?

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

What is the use of constructor in enum?

Example: enum Constructor The constructor takes a string value as a parameter and assigns value to the variable pizzaSize . Since the constructor is private , we cannot access it from outside the class. However, we can use enum constants to call the constructor.

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

Can enum have constructors C++?

A type defined with enum class or enum struct is not a a class but a scoped enumeration and can not have a default constructor defined. The C++11 standard defines that your PinID pid = PinID(); statement will give a zero-initialization.


1 Answers

Why not create an extension method to do this for you?

public static class ExtensionMethods
{
    public static MessageType ConvertMessageType(this JabberMessageType jabberType)
    {
        switch(jabberType)
        {
            case JabberMessageType.normal:
                return MessageType.Normal;
            // Add rest of types here.
            default:
                return MessageType.Error;
        }
    }
}

Example usage:

var type = JabberMessageType.normal; // JabberMessageType
var messageType = type.ConvertMessageType(); // Converted to your custom MessageType
like image 64
Johannes Kommer Avatar answered Oct 12 '22 22:10

Johannes Kommer