tags:

views:

170

answers:

3

I want to use an object (returned by framework, not in my control), myField which has a property DisplayFormat of type enum SPNumberFormatTypes.

I want to assign the integer value of DisplayFormat as a string to an XmlAttribute. Here is what I currently do:

myAttribute.Value = ((Int32)((SPNumberFormatTypes)field.DisplayFormat)).ToString();

One more possible way to achieve this is:

myAttribute.Value = ((Int32)Enum.Parse(typeof(SPNumberFormatTypes), field.DisplayFormat.ToString())).ToString();

I want to know if there is a simpler/cleaner way to achieve this?

A: 

How about an extension method?

http://msdn.microsoft.com/en-us/library/bb383977.aspx

James
+1  A: 

Yes, refactor what you have into an extension method, say, ValueToString:

public static string ValueToString(this SPNumberFormatTypes format) {
    int value = (int)format;
    return format.ToString();
}

Usage:

// format is SPNumberFormatType
Console.WriteLine(format.ValueToString());

Also, the name of your enum should be singular so SPNumberFormatType. For each member of your enum, say Foo, SPNumberFormatType.Foo is a format type, not a format types. This is why it should be singular. If, however, SPNumberFormatTypes is marked as Flags then you're fine, plural is standard but you should rename DisplayFormat to DisplayFormats.

Here are the naming guidelines from MSDN.

Jason
@Aaronaught: It is most likely not a flag by it's name having the substring "NumberFormat" and being assigned to a member named "DisplayFormat." You are right though that plural is de rigueur for flags.
Jason
+1  A: 

@itowlson's comment is the correct answer. Since the enum is already of type SPNumberFormatTypes, there is no need to cast it to that type. Thus my objective can be acheived in an easier way by doing this:

((Int32)(field.DisplayFormat)).ToString();

Thanks @itowlson!

desigeek