I have class MyWord and many other classes such as Noun, Idiom etc. that inherits from MyWord.
I store those objects in one list:
List<MyWord> Dictionary;
When I Add new element to the list i do it like this:
var myWord = new MyWord(id, word, definition,type,DateTime.Now.ToShortDateString());
Dictionary.Add(myWord);
As you can see, I put there object MyWord. I would like to be able to create for example Noun object and put in into list, like this:
var myWord = new Noun(id, word, definition, type, DateTime.Now.ToShortDateString());
Dictionary.Add(myWord);
The type parameter is a string, for example "noun". I use this method to get Type based on this string:
private Type GetFullType(string myType)
{
//Returns list of all types that inherit from MyWord class
var supportedTypes = (AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type.IsSubclassOf(typeof(MyWord)))).Select(x => x.FullName).ToList();
return Type.GetType(supportedTypes.Find(x => x.Contains_SkipWhiteSpacesIgnoreCase(myType)));
}
Now I don't know how to use the GetFullType() return value to convert MyWord to Noun. Like this:
Type wordType = GetFullType(type);
var myWord = new MyWord(id, word, definition, type, DateTime.Now.ToShortDateString());
Dictionary.Add((wordType)myWord);
I hope I explained myself clearly.
Note that I could use If...else structure to create different objects checking the type variable but it's not an elegant solution. Any better ideas?