<p>So if I have a method of parsing a text file and returning a <strong>list</strong> <em>of a</em> <strong>list</strong> <em>of</em> <strong>key value pairs</strong>, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?</p>
<p>The first method that pops into mind is pretty simple, just keep a list of keywords:</p>
<pre><code>private const string NAME   = &quot;name&quot;;
private const string PREFIX = &quot;prefix&quot;;
</code></pre>
<p>and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?</p>
<h1>Edit:</h1>
<p>More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:</p>
<pre><code>-
key: value 
key: value
-
key: value
key: value
-
</code></pre>
<p>Where the '-' line denotes a new section/object.</p>

[{'answer_id': 49772, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 1, 'selected': False, 'text': '<p>You could create an interface that matched the column names, and then use the Reflection.Emit API to create a type at runtime that gave access to the data in the fields.</p>\n'}, {'answer_id': 49782, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 2, 'selected': False, 'text': '<p>Take a deep look at the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="nofollow noreferrer">XmlSerializer</a>. Even if you are constrained to not use XML on-disk, you might want to copy some of its features. This could then look like this:</p>\n\n<pre><code>public class DataObject {\n  [Column("name")]\n  public string Name { get; set; }\n\n  [Column("prefix")]\n  public string Prefix { get; set; }\n}\n</code></pre>\n\n<p>Be careful though to include some kind of format version in your files, or you will be in hell\'s kitchen come the next format change.</p>\n'}, {'answer_id': 49785, 'author': 'Argelbargel', 'author_id': 2992, 'author_profile': 'https://Stackoverflow.com/users/2992', 'pm_score': 2, 'selected': False, 'text': "<p>What do you need object for? The way you describe it, you'll use them as some kind (of key-wise) restricted map anyway. If you do not need some kind of inheritance, I'd simply wrap a map-like structure into a object like this:</p>\n\n<pre>[java-inspired pseudo-code:]<code>\nclass RestrictedKVDataStore {\n   const ALLOWED_KEYS = new Collection('name', 'prefix');\n   Map data = new Map();\n\n   void put(String key, Object value) {\n      if (ALLOWED_KEYS.contains(key))\n          data.put(key, value)\n   }\n\n   Object get(String key) {\n      return data.get(key);\n   }\n}\n</code></pre>\n"}, {'answer_id': 49786, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 0, 'selected': False, 'text': "<p>@David:<br>\nI already have the parser (and most of these will be hand written, so I decided against XML). But that looks like I really nice way of doing it; I'll have to check it out. Excellent point about versioning too. </p>\n\n<p>@Argelbargel:<br>\nThat looks good too. :')</p>\n"}, {'answer_id': 49793, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 2, 'selected': False, 'text': '<p>Making a lot of unwarranted assumptions, I think that the best approach would be to create a Factory that will receive the list of key value pairs and return the proper object or throw an exception if it\'s invalid (or create a dummy object, or whatever is better in the particular case).</p>\n\n<pre><code>private class Factory {\n\n   public static IConfigurationObject Factory(List&lt;string&gt; keyValuePair) {\n\n       switch (keyValuePair[0]) {\n\n          case "x":\n              return new x(keyValuePair[1]);\n              break;\n          /* etc. */\n          default:\n              throw new ArgumentException("Wrong parameter in the file");\n       }\n\n  }\n\n}\n</code></pre>\n\n<p>The strongest assumption here is that all your objects can be treated partly like the same (ie, they implement the same interface (IConfigurationObject in the example) or belong to the same inheritance tree).</p>\n\n<p>If they don\'t, then it depends on your program flow and what are you doing with them. But nonetheless, they should :)</p>\n\n<p>EDIT: Given your explanation, you could have one Factory per file type, the switch in it would be the authoritative source on the allowed types per file type and they probably share something in common. Reflection is possible, but it\'s riskier because it\'s less obvious and self documenting than this one.</p>\n'}, {'answer_id': 49869, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p><em>...This is a fairly core piece of the</em>\n  <em>project I'm working on though...</em></p>\n</blockquote>\n\n<p>Is it really? </p>\n\n<p>It's tempting to just abstract it and provide a basic implementation with the intention of refactoring later on.</p>\n\n<p>Then you can get on with what matters: the game.</p>\n\n<p>Just a thought</p>\n\n<p>&lt;bb /&gt;</p>\n"}, {'answer_id': 49875, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>Is it really?</p>\n</blockquote>\n\n<p>Yes; I have thought this out. Far be it from me to do more work than neccessary. :') </p>\n"}, {'answer_id': 49899, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': '<p><strong>EDIT:</strong> </p>\n\n<p>Scratch that, this still applies, but I think what your doing is reading a configuration file and parsing it into this:</p>\n\n<pre><code>List&lt;List&lt;KeyValuePair&lt;String,String&gt;&gt;&gt; itemConfig = \n    new List&lt;List&lt;KeyValuePair&lt;String,String&gt;&gt;&gt;();\n</code></pre>\n\n<p>In this case, we can still use a reflection factory to instantiate the objects, I\'d just pass in the nested inner list to it, instead of passing each individual key/value pair.</p>\n\n<p><strong>OLD POST:</strong></p>\n\n<p>Here is a clever little way to do this using reflection:</p>\n\n<p>The basic idea:</p>\n\n<ul>\n<li>Use a common base class for each Object class.</li>\n<li>Put all of these classes in their own assembly.</li>\n<li>Put this factory in that assembly too.</li>\n<li>Pass in the KeyValuePair that you read from your config, and in return it finds the class that matches KV.Key and instantiates it with KV.Value</li>\n</ul>\n\n<pre>   \n      public class KeyValueToObjectFactory\n      { \n         private Dictionary _kvTypes = new Dictionary();\n\n        public KeyValueToObjectFactory()\n        {\n            // Preload the Types into a dictionary so we can look them up later\n            // Obviously, you want to reuse the factory to minimize overhead, so don\'t\n            // do something stupid like instantiate a new factory in a loop.\n\n            foreach (Type type in typeof(KeyValueToObjectFactory).Assembly.GetTypes())\n            {\n                if (type.IsSubclassOf(typeof(KVObjectBase)))\n                {\n                    _kvTypes[type.Name.ToLower()] = type;\n                }\n            }\n        }\n\n        public KVObjectBase CreateObjectFromKV(KeyValuePair kv)\n        {\n            if (kv != null)\n            {\n                string kvName = kv.Key;\n\n                // If the Type information is in our Dictionary, instantiate a new instance of that class.\n                Type kvType;\n                if (_kvTypes.TryGetValue(kvName, out kvType))\n                {\n                    return (KVObjectBase)Activator.CreateInstance(kvType, kv.Value);\n                }\n                else\n                {\n                    throw new ArgumentException("Unrecognized KV Pair");\n                }\n            }\n            else\n            {\n                return null;\n            }\n        }\n    }\n</pre>\n'}]
['https://Stackoverflow.com/questions/49757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61/']