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.
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.
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.
You can use extension methods to add functionality specific to a particular enum type.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With