I want to declare a variable like this in C#
public anyType variable;
and then I can use it like this
variable["name1"] = anyValue1;
variable["name2"] = anyValue2;
I cannot find out any solution to declare what type of variable is to use it that way.
Please help me.
I appreciate any comments
Additional information:
I have a class:
public class Template
{
public string Name {get; set; }
public string Content {get; set;}
}
I want to set value for Template Content and Template Name like this
Template t = new Template();
t["Name"] = "template1";
t["Content"] = "templatecontent1";
not:
Template t = new Template();
t.Name = "template1";
t.Content = "templatecontent1";
I mean like a table attribute. Here I have table Template, it has 2 columns Name and Content. So that I can query Template[“Name”] and Template[“Content”]
Thanks
The type you need is
Dictionary<string, object>. You can substituteobjectfor whatever the type ofanyValue1andanyValue2is.EDIT: To allow indexers to set properties, you’ll almost certainly need reflection. Try this setter on your
Templateclass:There’s no error handling in the above example though, so it’ll fail horribly if you try setting a property that doesn’t exist, or isn’t a string, or doesn’t have a getter/setter. You will need to add
using System.Reflectionto your uses clauses.