Reputation: 187
I have an enum list with assigned int values, if I understand correct. I need to keep the leading 0 so is there a way to consider this value a string and not an int?
My enums
public enum CsvRowFormat
{
BeginningOfFile = 01,
School = 02,
Student = 03,
EndOfFile = 04
}
Currently I'm reading out the value like this which I find inefficient
studentRowFormat.AppendFormat("0{0}",(int)TransactionFile.CsvRowFormat.Student).ToString();
Upvotes: 0
Views: 2106
Reputation: 203827
You can use "{0:D2}"
as the format string. It will pad the string with leading zeros until it is of length 2.
The enum
you are using is just storing the numeric value of what you are assigning, not the string value, so it doesn't retain knowledge of the fact that you supplied a leading zero. Native enum
types cannot be backed by a string; they must be backed by an integer value. You can create your own custom type that "looks" like it's a string-backed enum, but using such a solution will be much more effort than just using a more proper format string with your existing integer enum
.
Upvotes: 4
Reputation: 2691
Unfortunately, there is not a way to consider the value as a string instead of an int. See C# Enum Reference. You could use the formatting options provided by the other answers, or you could write a struct that would allow your code to be much cleaner. Because I don't know your reasons for using an enum, I feel I must point out that structs have some behavioral differences. Here is an example of using a struct for this solution:
public struct CsvRowFormat
{
public string Value { get; private set; }
private CsvRowFormat(string value) : this()
{
Value = value;
}
public static BeginningOfFile { get { return new CsvRowFormat("01"); } }
public static School { get { return new CsvRowFormat("02"); } }
public static Student { get { return new CsvRowFormat("03"); } }
public static EndOfFile { get { return new CsvRowFormat("04"); } }
}
Sample Usage:
studentRowFormat.Append(TransactionFile.CsvRowFormat.Student);
Hope this helps!
Upvotes: 0
Reputation: 2394
Int32 has a ToString() that takes a format string. So the easiest way is something like this:
studentRowFormat.Append(((int)TransactionFile.CsvRowFormat.Student).ToString("D2"));
You don't need the leading 0 in the enum declarations.
Upvotes: 3