0
Outputs.RunParams.RunAlgorithm = Convert.ChangeType(AlgString,typeof(RunAlgorithmConstants));

I'm trying to set a Run Parameter for a program to a specific value, but the AlgString is a string and I need it to be of the type RunAlgorithmConstants. AlgString being a string is a result of converting from type RunAlgorithmConstants to string directly in a previous script, saving it to a text file, reading from that text file, and setting the text to AlgString.

When I run this code I get this error:

Cannot implicitly convert type 'object' to 'RunAlgorithmConstants'. An explicit conversion exists (are you missing a cast?)

The namespace is fine. I could write

if (AlgString.Equals("Example1"))
{
Outputs.RunParams.RunAlgorithm = RunAlgorithmConstants.Example1
}

for every possible value that RunAlgorithmConstants could be but I was wondering if there is an easier way.

Edit:

int LineNumber = Inputs.LineNumber;


var lines = File.ReadAllLines(Inputs.LoadLocation);


string line = lines[LineNumber];


{char[] delimiterChars = {','};


  string[] words = line.Split(delimiterChars);
  words[30] = AlgString
6
  • 1
    Your error message says an explicit conversion exists, have you tried explicitly casting it? Commented Jun 16, 2015 at 20:45
  • Also: RunAlgorithmConstants is a type defined under the program in the namespace Commented Jun 16, 2015 at 20:46
  • What the hell is in AlgString? "Two slices of bolognia and a slice of cheese please"? Why should a string be converted magically into a RunAlgorithmConstants? Commented Jun 16, 2015 at 20:50
  • Just tried explicitly casting it, gave me an Error saying it cannot convert string to RunAlgorithmConstants. Commented Jun 16, 2015 at 20:51
  • AlgString is a direct conversion from a RunAlgorithmConstants value to string so that it could be saved in a text file for records. Now, I'm loading lines from that text file so I can use it as input for my program to replicate the conditions that the program was previously in. Commented Jun 16, 2015 at 20:54

1 Answer 1

1

Enum.Parse is what you are looking for:

Outputs.RunParams.RunAlgorithm = (RunAlgorithmConstants) Enum.Parse(typeof(RunAlgorithmConstants), AlgString);
Sign up to request clarification or add additional context in comments.

3 Comments

It's giving me the same error as before. I appreciate the help though.
Is the type of your Outputs.RunParams.RunAlgorithm an object? It would be useful for you to show the declarations of AlgString and your enum and probably RunAlgorithm.
Edited in above The enumeration is built into the program I am using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.