Reputation: 457
I have been trying to create a class which has a property for key value pair, I have tried the Dictionary keyword, but I need something like this:
ClassName clsName = new ClassName();
clsName.PropertyName.Add["Key"] = value;
I want it to be dynamic property so I can send any datatype.
Upvotes: 6
Views: 47683
Reputation: 53958
If we suppose that KeyValuePair
has as a key as a string
, and a value as int
, then you could try this:
clsName.PropertyName = new KeyValuePair<string, int>("keyName", 2);
You don't need to use the Add
method. Actually, the latter makes sense when you have a collection and don't want to add an item to it. From what you have posted in your question, we can't say that this is your case.
Upvotes: 9
Reputation: 17605
I'm not sure if I understood the question correctly, but apparently your requirements can be met using a generic Dictionary, where the key type parameter is string
and the value type parameter is object
, i.e. you could use Dictionary<string,object>
like this:
public class ClassName {
public Dictionary<string, object> Dictionary { get; set; }
}
And then:
ClassName classObject = new ClassName();
classObject.Dictionary.Add("Key", new { "value" });
Upvotes: 1
Reputation: 1075
public class ClassName
{
public KeyValuePair<string, object> PropertyName {get; set; }
}
var c = new ClassName();
c.PropertyName = new KeyValuePair<string, object>("keyName", someValue);
or, if you need to store multiple values, use Dictionary<string, object>
as type of your property.
public class ClassName
{
public ClassName()
{
this.PropertyName = new Dictionary<string, object>();
}
public Dictionary<string, object> PropertyName {get; set; }
}
var c = new ClassName();
c.PropertyName.Add("stringKey", anyValue);
Upvotes: 1
Reputation:
I suggest you to simply use the "HASHTABLE" its so much easier for you.Below is syntax.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
1st parameter represents the key and 2nd one represents the value.So its the key value pair.
Upvotes: 6
Reputation: 1276
If you are after a basic class, for key and value, would
KeyValuePair<string, object>
work for you?
Upvotes: 3