This question already has answers here:
Enum ToString with user friendly strings
(25 answers)
Closed 7 years ago.
I need my enum to return a formatted string to the view, for example:
public enum status
{
NotStarted,
InProgress,
}
return: Not Started and In Progress. How I do it? Thanks (language C#)
enums don't do that. You'd need to provide a map of enum values to display strings or you could do something like define an attribute with a display string that you can use (which requires some fiddly reflection to get the attribute for a given enum value, but has the advantage that you can define the display name right where you define the enum value).
For example, you can use a Dictionary<status,string> to map them:
var myMap = new Dictionary<status,string>()
{
{ status.NotStarted, "Not Started" },
{ status.InProgress, "In Progress" }
};
Now to get the display string for a given status value s you'd just do something like:
var s = status.NotStarted;
var displayString = myMap[s]; // "Not Started"
Of course, you'd put this in a class somewhere so it's only defined once in one place.
Another rather brittle, quick-and-dirty way to do it would be to exploit the fact that your enum names are Pascal-cased and use something like a regex to take the enum name and insert an extra space. But that's pretty hacky. So you could do something like:
var r = new Regex("([A-Z][a-z]*)([A-Z][a-z]*)");
var displayString = r.Replace(s.ToString(),"$1 $2"); // "Not Started"
But that would choke on any enum values that didn't fit the pattern of two Pascal-cased words. Of course, you could make your regex more flexible, but that's beyond the scope of the question.
Calling ToString on an emum value is the equivalent to Enum.GetName which would give you the named value i.e.
Console.WriteLine(status.NotStarted.ToString()) // NotStarted
From there, assuming the format is consistent, you could convert the string from Pascal casing to a whitespace separated string e.g.
string result = Regex.Replace(status.NotStarted, "([a-z])([A-Z])", "$1 $2");
Console.WriteLine(result); // Not Started
See example.
Enum.GetName(typeof (Status), Status.InProgress));
Related
This question already has answers here:
String interpolation C#: Documentation of colon and semicolon functionality
(2 answers)
Closed 1 year ago.
using System;
public class Example
{
public static void Main()
{
Console.WriteLine ($"{1:5d}");
}
}
// The example displays the following output:
// 5d
What does the ":" do in the interpolated string?
I know if I write,
$"{1:d5}"
I will get,
00001
but with this I'm not getting an error/warning means it has to mean something that I don't know.
FYI, I'm on C#7.
It is separator for format string. It allows you to specfy formatting relevant to the type of value on the left. In first case it tries to apply custom format, but since there is no placeholder for actual value - you get only the "value" of the format (try something like Console.WriteLine ($"{1:00000SomeStringAppended}"); for example, "5d" has the same meaning as "SomeStringAppended" in my example). The second one - d5 is a standart decimal format specifier, so you get corresponding output containing formatted value.
The following two line would be give the same results - 00001.
var i = $"{1:d5}";
var j = string.Format("{0:d5}", 1);
A colon : in curly brackets is string formatting.
You can read more about string formatting here and about string formatting in a string interpolation here
This question already has answers here:
What's the use/meaning of the # character in variable names in C#?
(9 answers)
Closed 19 days ago.
I understand that the # symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the # symbol?
The # symbol allows you to use reserved word. For example:
int #class = 15;
The above works, when the below wouldn't:
int class = 15;
The # symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int #int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = #"c:\myFolder\myfile.txt"
An important point that the other answers forgot, is that "#keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int #this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
It allows you to use a C# keyword as a variable. For example:
class MyClass
{
public string name { get; set; }
public string #class { get; set; }
}
This question already has answers here:
Is it possible to add a string with spaces or special characters to an enum?
(2 answers)
Closed 8 years ago.
I have an enumeration as below
private enum gettype
{
Xml/adf = 1,
xml/adf and html = 2
};
but as of my knowledge I know that we could not declare special characters spaces in between.
I even tried "display" and "description" though didn't work.
So does any one know any work around.
You cannot. Enum members must be valid C# identifiers. You can decorate them with a variety of attributes, however:
using System.ComponentModel;
private enum gettype
{
[Description("Xml/adf")]
XmlAdf = 1,
[Description("Xml/adf and html")]
XmlAdfAndHtml = 2
}
Now to convert the enum value to a description string, or vice versa you'd have to use reflection, one way or other. For example:
var enumValue = gettype.XmlAdfAndHtml;
var attr = (DescriptionAttribute[])
typeof(gettype).GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), true);
var stringValue = attr[0].Description; // Xml/adf and html
Refers the below stack overflow links which may helpful to you.
Is it possible to add a string with spaces or specialcharacters to an enum
How can I use a special char in a C# enum?
I have implemented URL mapping in our ASP.NET 4 application, but I have a problem with some of our content.
Some of our products has a hyphen "-" or a question mark "?" in them. It's not an option to remove that. A productname could be "My Product - Good for you?".
We use two custom made methods, MakeUrlSeoReady and MakeUrlNonSeoReady. We replace space like this: Replace(" ","-"), as this is the most SEO-friendly solution. However, we also need to make this work with both question marks and hyphens.
The reason we use the MakeUrlSeoReady / NonReady methods is to be able to show the "real" name.
Currently the mapping is defined as follows:
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductName}",
"~/SingleProduct.aspx");
So what I do is I retrieve the product depending on the ProductName. I use two methods I've created:
public static string MakeUrlNonSeoReady(string text)
{
return text.ToLower().
Replace("oe", "ø").
Replace("aa", "å").
Replace("ae", "æ").
Replace("-", " ");
}
public static string MakeUrlSeoReady(string text)
{
return text.ToLower().
Replace("ø", "oe").
Replace("å", "aa").
Replace("æ", "ae").
Replace(" ", "-");
}
So in the SingleProduct.aspx page I use the following string to get from our database:
string categoryName = HelperFunctions.MakeUrlNonSeoReady(Page.RouteData.Values["ProductName"]);
But this will of course not work. So any help is really appreciated :-)
An arguably cleaner and simpler method is to use a unique product identifier that is numerical or alphanumerical and is natively HTML encoded, and then simply put the product name as an unused parameter for SEO or search purposes.
MSDN RouteCollection.MapPageRoute Method (String, String, String, Boolean, RouteValueDictionary)
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductIdentifier}/{ProductName}",
"~/SingleProduct.aspx", false, new RouteValueDictionary
{ { "ProductName ", string.Empty } });
This question already has answers here:
What's the use/meaning of the # character in variable names in C#?
(9 answers)
Closed 22 days ago.
I understand that the # symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the # symbol?
The # symbol allows you to use reserved word. For example:
int #class = 15;
The above works, when the below wouldn't:
int class = 15;
The # symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int #int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = #"c:\myFolder\myfile.txt"
An important point that the other answers forgot, is that "#keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int #this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
It allows you to use a C# keyword as a variable. For example:
class MyClass
{
public string name { get; set; }
public string #class { get; set; }
}