0

i will discuss my case to make a good understand for my question at first i am getting data from my api client as my class :

 return JsonConvert.DeserializeObject<TestRespone>(responseContent);

so i get the data of my class : which is

public enum TestStatus
{
   Sucess,
    Error
}
public class TestRespone
{
    public enum TestStatus{ get; set; }
    public string  Message { get; set; }
}

However i get the Teststatus from api as a string but i want to apply as an enum immediatly in my code : i wrote extra code :

 public static TestStatus ToTestStatus(this string s)
        {
            switch (s)
            {
                case "INITIALIZED":
                    return SignatureStatus.Sucess;

                case "SIGNED":
                    return SignatureStatus.Error;
            }
         }

my question is how to custmize public enum TestStatus to be immediatly an enum cause it alreay come as a sring ? i mean i get it from api as string but i want it in class like enum

2

2 Answers 2

0

No directly you can't do it, But if you must you should use Custom Contract resolver

0

I managed to create something similar to what you want but the clutter is huge:

public enum TestStatus {
        Sucess,
        Error
            ///etc
    }
    public static class Ext {
    public static TestStatus ToTestStatus(this string target) {
        TestStatus testStatus;
        var enumerator = Enum.GetValues(typeof(TestStatus)).GetEnumerator();

        while (enumerator.MoveNext()) {
            if ((testStatus=((TestStatus)enumerator.Current)).ToString() == target) {
                return testStatus;
            }

        }
        return TestStatus.Error; //some default;

    }
}

Usage:

TestStatus c = "Error".ToTestStatus();
TestStatus d = "Success".ToTestStatus();

Refined it a bit :D

Not the answer you're looking for? Browse other questions tagged or ask your own question.