Dynamically create instance(s) of C# class - c#

I want to dynamically create instances of a class, so I created a dictionary of objects of that class and assign the names by appending a counter to a string. But how do I access the properties of the objects?
The code is something like this:
int count = 0;
string name = "MyInstanceName" + count.ToString();
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass(Parameter));
//try to retrieve the Property - this doesn't work
textBox1.Text = d[name.Property];

You can do this
int count = 0;
string name = "MyInstanceName" + count.ToString();
var d = new Dictionary<string, MyClass>();
d.Add(name, new MyClass());
textBox1.Text = d[name].Property;
You created a Dictionary that the key is a string and the value is a instance of MyClass.
When using Dictionary index, the value between brackets [] should be the key, in this case a string.
myDictionary["keyValue"]

textBox1.Text = d[name].Property;

in addition to Alberto Monteiro's answer, don't forget to cast your object:
textBox1.Text = (myClass) d["MyInstanceName1"].Property;
or
var myInstanceX = d["MyInstanceName1"].Property;
textBox1.Text = myInstanceX.myStringProperty();
In C# (unlike VB), you don't need to specify the type of a variable if the compiler can determine it elsewhere, so you can also simplify:
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
into
var d = new Dictionary<string, MyClass>();
var is a typed variable declarator (unlike javascript)

Related

Create number of new class objects from dictionary count

int proprtyCount = dictionary.Keys.Count;
foreach (KeyValuePair<object, object> pair in dictionary)
{
ClassCustom obj1 =new ClassCustom(pair.Key, pair.Value);
}
I need to create number objects using dictionary.keys.count and pass those objects to some collection class.
i have to pass objects like below to collection (eg.dictionary key count is 3 in this case)
SomeCollection collection =new SomeCollection(obj1,obj2,obj3);
Why don't you assign it to a list?
int proprtyCount = dictionary.Keys.Count;
var classCustomList = new List<ClassCustom>();
foreach (KeyValuePair<object, object> pair in dictionary)
{
classCustomList.Add(new ClassCustom(pair.Key, pair.Value));
}
SomeCollection collection = new SomeCollection(classCustomList);
Have the SomeCollection class initialize a list of type classCustomList in it's constructor.
Update: If it's some sort of collection class, maybe try doing something similar to
int proprtyCount = dictionary.Keys.Count;
var conditions = new PropertyCondition[propertyCount];
int index = 0;
foreach (KeyValuePair<object, object> pair in dictionary)
{
conditions[i] = new PropertyCondition(pair.Key, pair.Value));
index++;
}
var conditionEnabledButtons = new AndCondition(conditions);
There's an overload with type array
Eg.
var conditions = new PropertyCondition[3];
conditions[0] = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
conditions[1] = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
var conditionEnabledButtons = new AndCondition(conditions);

Json.Net, how to create json dynamically by path?

I'm new to Json.net, so I'm not sure if I'm doing this the right / best way, but I can't figure this out:
I'm creating an output JObject:
JObject joOutput = new JObject();
Now, I have a list of paths to values:
a.b.c = 5
a.b.d = 7
a.c.q = 8
So I want to populate the joOutput object in the obvious way using that hierarchy.
I can't seem to find a way to set the value by path, obviously creating the path along the way if it doesn't exist.
I'm trying to split the path on the .'s and create the nodes, but I can't even get that far as the api is very confusing.
Can you point me in the right direction?
Thanks!
string a = #"{""b"": {""c"":5, ""d"":7}, ""c"": {""q"":8}}";
JObject joObject = JObject.Parse(a);
UPDATE:
var B = new JObject();
B.Add("c", 5);
B.Add("d", 7);
var C = new JObject();
C.Add("q", 8);
JObject A = new JObject();
A.Add("b", B);
A.Add("c", C);
UPDATE2, for completeness, here is Vladimir's method:
var B = new Dictionary<string, int> { ["c"] = 5, ["d"] = 7 };
var C = new Dictionary<string, int> { ["q"] = 5, ["8"] = 7 };
var A = new Dictionary<string, object> { ["b"] = B, ["c"] = C };
var AA = JObject.FromObject(A);
Try to solve your problem by using Dictionary with string key and object value.
Dictionary<string,object> myJsonObj = new Dictionary<string, object>;
Each element inside can be also same dictionary.

splitting string in dictionary

How do I split the following string
string s = "username=bill&password=mypassword";
Dictionary<string,string> stringd = SplitTheString(s);
such that I could capture it as follows:
string username = stringd.First().Key;
string password = stringd.First().Values;
Please let me know. Thanks
You can populate the dictionary list like so:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string s = "username=bill&password=mypassword";
foreach (string x in s.Split('&'))
{
string[] values = x.Split('=');
dictionary.Add(values[0], values[1]);
}
this would allow you to access them like so:
string username = dictionary["username"];
string password = dictionary["password"];
NOTE: keep in mind there is no validation in this function, it assumes your input string is correctly formatted
It looks like you are trying to parse a query string - this is already built in, you can use HttpUtility.ParseQueryString() for this:
string input = "username=bill&password=mypassword";
var col = HttpUtility.ParseQueryString(input);
string username = col["username"];
string password = col["password"];
I think something similar to this should work
public Dictionary<string, string> SplitTheStrings(s) {
var d = new Dictionary<string, string>();
var a = s.Split('&');
foreach(string x in a) {
var b = x.Split('=');
d.Add(b[0], b[1]);
}
return d;
}
var splitString = "username=bill&password=pass";
var splits = new char[2];
splits[0] = '=';
splits[1] = '&';
var items = splitString.Split(splits);
var list = new Dictionary<string, string> {{items[1], items[3]}};
var username = list.First().Key;
var password = list.First().Value;
this my also work
If Keys will not repeat
var dict = s.Split('&').Select( i=>
{
var t = i.Split('=');
return new {Key=t[0], Value=t[1]};}
).ToDictionary(i=>i.Key, i=>i.Value);
If Keys can repeat
string s = "username=bill&password=mypassword";
var dict = s.Split('&').Select( i=>
{
var t = i.Split('=');
return new {Key=t[0], Value=t[1]};}
).ToLookup(i=>i.Key, i=>i.Value);
The other answers are better, easier to read, simpler, less prone to bugs, etc, but an alternate solution is to use a regular expression like this to extract all the keys and values:
MatchCollection mc = Regex.Matches("username=bill&password=mypassword&","(.*?)=(.*?)&");
Each match in the match collection will have two groups, a group for the key text and a group for the value text.
I am not too good at regular expressions so I don't know how to get it to match without adding the trailing '&' to the input string...

Converting a string to a variable name

public static string filename2_1, filename2_2, filename2_3;
filename2_1="xyz.jpg";
filename2_2="abc.png";
filename2_3="qwe.jpg";
.....
...
for (int key = 1; key <= 3; key++)
{
....
foreach (var item in tabItem)
{
item.ImagePath.Value = "images1/" + ("filename2_" + key);
item.ThumbPath.Value = "thumbnails1/" + ("filename2_" + key);
}
}
As stated above I need to convert ("filename2_" + key) into actual variable. Can anyone help me regarding this
You can't have dynamic variable names.
Variable names cannot be "created".
You can use an array or a generic collection to hold the collections of data you are using.
var fileSuffixList = new List<string>{ "xyz.jpg" , "abc.png", "qwe.jpg"};
foreach(string fileSuffix in fileSuffixList)
{
....
foreach (var item in tabItem)
{
item.ImagePath.Value = "images1/" + ("filename2_" + fileSuffix);
item.ThumbPath.Value = "thumbnails1/" + ("filename2_" + fileSuffix);
}
}
As #Oded stated, you can't have dynamic variable names.
What you can do is use a Collection such as a dictionary:
Dictionary<string, int> dictionary = new Dictionary<string, string>();
dictionary.Add("filename2_" + key, "Value");
If your keys are always numeric, you can also use an array or a List. However, without more information, it's hard to tell you the best way to go about it.

How do I name variables dynamically in C#?

Is there a way to dynamically name variables?
What I need to do is take a list of variable names from an input file and create variables with those names. Is this possible?
Something like:
Variable <dynamic name of variable here> = new Variable(input);
Assume that I already have the Variable class taken care of, and the name of the variable is contain in a string called strLine.
Use a Dictionary<string, Variable>.
e.g.
var vartable = new Dictionary<string, Variable>();
vartable[strLine] = new Variable(input);
C# 4.0, using the dynamic objects:
dynamic d = new ExpandoObject();
((IDictionary<string, object>)d)["MyProperty"] = 5;
int val = d.MyProperty; // 5
No, but you could use a Dictionary<string, Variable>, and then you can refer to each variable by its quoted name.
You can't do that, but what you're looking to do is begging for a Dictionary use:
Dictionary<object, object> d = new Dictionary<string, object>();
d.Add("Variable1", value1);
d.Add("Variable2", value2);
d.Add("Variable3", value3);
try this one,user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
Variable names should be known at compile time. If you intend to populate those names dynamically at runtime you could use a List<T>.
var variables = List<Variable>();
variables.Add(new Variable { Name = input1 });
variables.Add(new Variable { Name = input2 });
...
No. You can load them into a Dictionary object, however. This allows you to still reference them (somewhat) using a name, which is a bit easier than using an Index, as you would with an Array or ArrayList.
I would use some sort of keyed collection, like a hashtable, dictionary, or list of structures with the name. You can then refer to the variable by name:
var value = variableDictionary["MyVariableName"];
var value = variableHashtable["MyVariableName"];
var value = variableList.First(x=>x.Name == "MyVariableName");
There is no other way to dynamically "name" a variable.
No. Use an array, otherwise you can't do this.

Categories

Resources