user4916753
user4916753

Reputation: 13

c# Converting from string to special type - "an explicit conversion exists"

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

Upvotes: 0

Views: 120

Answers (1)

Aaron D
Aaron D

Reputation: 5886

Enum.Parse is what you are looking for:

Outputs.RunParams.RunAlgorithm = (RunAlgorithmConstants) Enum.Parse(typeof(RunAlgorithmConstants), AlgString);

Upvotes: 1

Related Questions