I'm making a program which when a chemical symbol of an element is entered, it'll return information of that element onto the form. This is simple to do but it want to try and keep my code as efficient as possible.
My dictionary:
Dictionary<string, object> alkaliM = new Dictionary<string, object>();
In my code also:
alkaliM.Add("Li", new AlkaliMetals.Lithium());
elementSymbol
is my input string from the textbox
I'm trying to set elementName.Text
to the property "name
" of my AlkaliMetals.Lithium
object. However, i can't simply put:
elementName.Text = alkaliM[elementSymbol.Text];
as i can't set an object as a string. ("Cannot implicty convert type "object" to "string"
")
Is there any way to set elementName.Text
to AlkaliMetals.Lithium.name
using only the key?
I have a separate file that has a main class AlkaliMetals
and subclasses for each of the alkali metals like Lithium
.
If my description doesn't make sense let me know and i'll try to explain what i mean.
You can make all the sub classes in AlkaliMetals.cs implement an abstract class
CommonAbstractClass
having the propertyname
Define you dictionary as
Dictionary<string, CommonAbstractClass>
Then use your dictionary as follows
elementName.Text = alkaliM[elementSymbol.Text].name;
You can find the
name
property (if you are absolutely sure it exists) using dynamic cast:However, a more efficient approach would be
Object Oriented Design
:Define a class named
ChemicalElement
, addname
property to it and then deriveLithium
fromChemicalElement
. This way you can write:Best solution is to define your dictionary like this:
And then access the
name
like: