Return FontStyle from string name

I want to write a function that will return a FontStyle and take a string as a parameter

FontStyle f = function ("Italic"); // FontStyles.Italic

I do not want to write a Switch statement or if else do the same.

Can this be done for case-insensitive strings?

FontStyle f = function ("italic");
FontStyle f = function ("itAlic"); 

should return the same.

+3
source share
2 answers

You can use reflection for this:

var propertyInfo = typeof(FontStyles).GetProperty("Italic",
                                                  BindingFlags.Static |
                                                  BindingFlags.Public |
                                                  BindingFlags.IgnoreCase);
FontStyle f = (FontStyle)propertyInfo.GetValue(null, null);
+5
source

In C #, this is just an enumeration. Therefore, you can convert it as follows:

FontStyle f = (FontStyle)Enum.Parse(typeof(FontStyle), "Italic", true);
+9
source

All Articles