-1

I have a class with is a collection of XPaths. I want to pass the name of the field and want to get the XPath for that field. The problem here is I have to store the passed value in a variable and putting an if condition to check for the corresponding XPath variable as shown below.

As of now, I am using the if condition and I can use switch condition as well but this solution is not feasible as the collection of XPath will grow and it will become unmanageable.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new Program().IReturnXpath("LastName"));
        }

        public string IReturnXpath(String nameOfField)
        {
            if (nameOfField.Equals("Lastname"))
                return new XpathCollection().Lastname;
            else if (nameOfField.Equals("Firstname"))
                return new XpathCollection().Firstname;
            else
                return "Xpath not found";
        }

        class XpathCollection
        {
            public string Lastname = "xpath for lastname";
            public string Firstname = "xpath for firstname";
        }
    }
  • 2
    [How to get a property value based on the name](//stackoverflow.com/q/5508050) – 001 Jul 03 '19 at 11:09
  • For your current example, it will be better to use `Dictionary` instead (or `Dictionary` if they are `XPath`s). – SᴇM Jul 03 '19 at 11:18

1 Answers1

0

Let me explain how Microsoft solved exact same problem.

System.Drawing.Color has many properties each reflecting a single color. Color also has a FromName method which allows you to find a color by string parameter. Almost exactly your problem.

As you can see in their, implementation, they create a Hashtable and by using reflection they fill it. Next time someone asks for a color they just lookup and return it. Put generation code in a static constructor and you are done.

https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/ColorConverter.cs,d06a69beb42834b2

Erdogan Kurtur
  • 3,630
  • 21
  • 39