1

I want to create a new XElement or XAttribute using an enum that stores the values. The constructor of both classes expects XName as name and object as content. This means that I can pass an enum as content but I need to use ToString() to use it in the name. Note that XName has an implicit operator for string.

This works:

new XElement(HttpStatusCode.Accepted.ToString(), (int)HttpStatusCode.Accepted)
new XElement(HttpStatusCode.Accepted.ToString(), HttpStatusCode.Accepted)

This doesn't work:

new XElement(HttpStatusCode.Accepted, (int)HttpStatusCode.Accepted)

Any suggestions how an enum can be for setting the name of an XElement?

Thanks.

Alex Kamburov
  • 405
  • 4
  • 10

2 Answers2

1

Enums are not implicitly convertible to strings.

C# does not currently have the capability to define extensions operators either.

An extension method may simplify this:

public static class EnumXmlExtensions
{
    public static XElement EncodeXElement(this Enum @enum)
    {
        return new XElement(@enum.ToString());
    }
}

Usage:

HttpStatusCode.Accepted.EncodeXElement(); // <Accepted />

See also:

Operator Overloading with C# Extension Methods

Community
  • 1
  • 1
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • `@enum.ToString()` works and is shorter. I saw that its implementation uses `InternalFormat()` which in turn uses `GetName()`. – Alex Kamburov Apr 03 '14 at 15:20
0

One solution I can think of is creating a utility method that will accept an object and convert it into XName and will create respective element/attribute. Something like:

    private static XElement NewElement(Enum name, params object[] content)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        return new XElement(name.ToString(), content);
    }
Alex Kamburov
  • 405
  • 4
  • 10