Casting string to enum [duplicate] - c#

This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 8 years ago.
I'm reading file content and take string at exact location like this
string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);
Output will always be either Ok or Err
On the other side I have MyObject which have ContentEnum like this
public class MyObject
{
public enum ContentEnum { Ok = 1, Err = 2 };
public ContentEnum Content { get; set; }
}
Now, on the client side I want to use code like this (to cast my string fileContentMessage to Content property)
string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);
MyObject myObj = new MyObject ()
{
Content = /// ///,
};

Use Enum.Parse().
var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}
And use it like so:
{
Content = ParseEnum<ContentEnum>(fileContentMessage);
};
Especially helpful if you have lots of (different) Enums to parse.

.NET 4.0+ has a generic Enum.TryParse
ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

Have a look at using something like
Enum.TryParse
Converts the string representation of the name or numeric value of one
or more enumerated constants to an equivalent enumerated object. A
parameter specifies whether the operation is case-sensitive. The
return value indicates whether the conversion succeeded.
or
Enum.Parse
Converts the string representation of the name or numeric value of one
or more enumerated constants to an equivalent enumerated object.

Related

How do you use a variable value to refer to another variable or object (i.e. EVAL in other languages) [duplicate]

This question already has answers here:
How to create dynamic incrementing variable using “for” loop in C#
(6 answers)
Closed 3 years ago.
Can I use a variable value as a reference in C# ? Consider the code below where 'myPointer' string holds the name of the variable I wish to output to the console... how can I do this ? As an extension to this I also wish to use the same approach to be able to reference multiple objects using a list of names in a dictionary - possible ?
string strVar1 = "Hello World";
string strVar2 = "Goodbye World";
int i = 1;
string myPointer = eval("strVar"+i); // there is no 'eval' in C#...
Console.WriteLine(myPointer); // I want to display the value of strVar1
There isn't anything similar to 'eval' in c#, but you can use reflection to create types or get properties by name.
So if you have something like this:
class MyCLass
{
string strVar1 ;
string strVar2 ;
}
First, get your type name by adding 1 to its name:
string typeName = "strVar" + "1";
Then you need to get property from class:
var myPropertyType = Typeof(MyClass).GetProperty(typeName);
After you can get the value of strvar1 by using the GetValue method:
var myValue = myPropertyType.GetValue(instance);
Where instance is your MyCLass's instance;
For more info read about reflection
P.S. Also. there are some NuGet packages for "Eval", but I don't know if they have the functionality you need.

The symbol 'new' in C#, what is its use? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have come across a problem upon viewing some tutorials on C# since I just started learning this language recently. I had a problem where once I had reversed a string I had to make use of new string in order to store its actual value in a different varible.
Why is the use of 'new string()' needed? In different programming languages I have never come across the need of using 'new string()'. Thanks in advance :)
//C#
char[] reversedName = name.ToCharArray();
Array.Reverse(reversedName);
string result = new string(reversedName);
String is a class like other classes in any Object oriented programming language and we can create object of it using new keyword like we would do for creating object of any type.
In your specific scenario above you have a char array and String class have a constructor overload which take char[] as input and create a String. So you call the constructor using new String.
So what is happening is you said to create an object of type string using char[] which is provided in the constructor of it.
You can - as in any other of your mentioned languages - of course also use something like this:
string m = "Hello World".
However your reversedName is an array of char, which is not convertible to string as is. So the following won´t work:
string myString = "Hello World".ToCharArray();
because ToCharArray - as the name suggests - returns char[], not string and there´s no conversion between the two.
That´s why you need to create a new string using the constructor that accepts an array of char.
The new-Keyword is used to create a new instance of your class.
If you want to assign one value of one type to another type you have to convert it in some way.
There are multiple ways:
Call a Constructor which accepts your input (You did this, because there is a constructor for string which accepts char[])
Use a Cast (No Cast available from char[] to string)
Use a Convert-Method (No available for converting values to string as far a I know)
Here an example-class which implements explicit and implicit casts (Which System.String does not):
class MyString
{
private string stringValues;
// Constructors
public MyString(char[] charArray) { stringValues = new string(charArray); }
public MyString(string str) { stringValues = str; }
public MyString() { }
// ToString for writing to console
public override string ToString() { return stringValues; }
// Operator to concat "MyStrings"
public static MyString operator +(MyString a, MyString b) { return new MyString(a.ToString() + a.ToString()); }
// Implicit Cast-operator string to MyString
public static implicit operator MyString(string str) { return new MyString(str); }
// Explicit Cast-operator char-array to MyString
public static explicit operator MyString(char[] str) { return new MyString(str); }
}
internal static void Main(string[] args)
{
MyString tmp = new MyString("Initialize by constructor with parameter string");
Console.WriteLine(tmp);
tmp = new MyString("Initialize by constructor with parameter char-array".ToCharArray());
Console.WriteLine(tmp);
tmp = new MyString("x") + new MyString("+") + new MyString("y");
Console.WriteLine("Use of '+ operator'" + tmp);
tmp = "Initialize by creating string and using implicit cast for strings";
Console.WriteLine(tmp);
tmp = (MyString)("Initialize by creating char-array and using explicit cast for strings".ToCharArray());
Console.WriteLine(tmp);
}

string to Enum in c# [duplicate]

This question already has answers here:
Search for a string in Enum and return the Enum
(13 answers)
Closed 9 years ago.
I need to assign a string to a Enum value. My scenario and code below
Am accessing a webservice method say addWhere(int i ,int j,Comparison)
Where Comparison is of type Enum.
Am fetching value from UI and having it in a string
string strComparison= "AND"; or
string strComparison= "OR"
i need to set these values to ENUM. I tried the below code
addWhere(2 ,3,Enum.Parse(typeof(Comparison),strComparison))
But didnt worked. What is the way to solve this or any alternate methods ?
Thanks
Looks like your missing the return cast i.e.
(Comparison)Enum.Parse(typeof(Comparison), strComparison);
Enum.Parse returns an object were as your addWhere method is expecting a Comparison type value.
You must cast the result of Enum.Parse to the correct type:
addWhere(2, 3, (Comparison)Enum.Parse(typeof(Comparison), strComparison));
You can do something like:
Comparison comparison;
if(Comparison.TryParse(strComparison, out comparison))
{
// Work with the converted Comparison
}
As said in earlier posts, you might be missing type casting.
enum Comparision
{
AND,
OR
}
class Program
{
static void Main(string[] args)
{
Comparision cmp = (Comparision)Enum.Parse(typeof (Comparision), "And", true);
Console.WriteLine(cmp == Comparision.OR );
Console.WriteLine(cmp == Comparision.AND);
}
}

An elegant way to get string from enum value? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a simple script to convert C++ enum to string?
In the C# program below, while using enumeration Priority, i need the string "None" and not the id 0. The C# code for doing this is given below. Is there an elegant way of doing this in C++. Can a map be avoided in the C++ implementation.
enum Priority
{
None,
Trivial,
Normal,
Important,
Critical
}
class Program
{
static void Main()
{
// Write string representation for Important.
Priority enum1 = Priority.Important;
string value1 = enum1.ToString();
// Loop through enumerations and write string representations. (See GetNames)
for (Priority enum2 = Priority.None; enum2 <= Priority.Critical; enum2++)
{
string value2 = enum2.ToString();
Console.WriteLine(value2); //outputs the string None, Trivial etc ...
}
}
}
public override string ToString()
{
Type type = base.GetType();
object obj2 = ((RtFieldInfo)GetValueField(type)).InternalGetValue(this, false);
return InternalFormat(type, obj2);
}
In C++, an enum is nothing more than a bit of syntactic sugar around an integral literal. The compiler quickly strips the enumerator name away, so the runtime never has access to it. If you want to have a string name for an enum, you have to do it the hard way.

Can I check if a format specifier is valid for a given data type?

If I have (in .NET/C#) for instance a variable of type long I can convert it to a formatted string like:
long value = 12345;
string formattedValue = value.ToString("D10"); // returns "0000012345"
If I specify a format which isn't valid for that type I get an exception:
long value = 12345;
string formattedValue = value.ToString("Q10"); // throws a System.FormatException
Question: Is there a way to check if a format specifier is valid (aside from trying to format and catching the exception) before I apply that format, something like long.IsFormatValid("Q10")?
Thanks for help!
I've not tried this but I would think you could create an extension method such as:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool IsFormatValid<T>(this T target, string Format)
where T : IFormattable
{
try
{
target.ToString(Format, null);
}
catch
{
return false;
}
return true;
}
}
}
which you could then apply thus:
long value = 12345;
if (value.IsFormatValid("Q0"))
{
...
Rather than creating a check for that I'd suggest that it might be better that the developers reads the documentation to find out what's allowed where.
However, if there is a problem with a lot of typos being made, I suppose you could write a lookup table from the information on that page. Though that could just give you a false sense of security in that you'd get people making mistakes between valid format specifiers (writing an f but they meant e etc).
Edited to remove confused bit about TryParse/Parse.

Categories

Resources