How can I dynamically create class objects?
I have a class MyClass
:
public class OPCTag
{
public string tagName;
public string tagOvationMatch;
public string tagValue;
}
I know how to create an object of a class manually, but how can I dynamically create objects of this class as well? For example, to create it in a loop for
:
for (int i=0; i< 10; i++)
{
//CREATE OBJECT DYNAMICALLY
}
To get 10 MyClass objects after it.
source to share
If you mean just instantiating a class always with the same type, this is enough for you:
List<OPCTag> list = new List<OPCTag>();
for (int i = 0; i < 10; i++)
{
// Create object of OPCTag
var obj = new OPCTag();
// Set value for 'tagName' property
obj.tagName = "New value of 'tagName'";
// Get value of 'tagName' property
var tagNameValue = obj.tagName;
list.Add(obj);
}
// Set value of 4th element 'tagName' property
list[4].tagName = "This is 4th element";
// Get value of 4th element 'tagName' property
var valueOf4thTag = list[4].tagName;
But if you want to dynamically create classes with unknown types, you must use reflection:
// Type namespace and name
string typeName = typeof(OPCTag).FullName; // MyNamespace.OPCTag
List<Object> list = new List<Object>();
for (int i = 0; i < 10; i++)
{
// Create object dynamically from string type
var obj = Type.GetType(typeName).GetConstructor(new Type[0]).Invoke(new object[0]);
// Set value for 'tagName' property
obj.GetType().GetProperty("tagName").SetValue(obj, "New value for 'tagName'");
// Get value from 'tagName' property
string tagNameValue = (string)obj.GetType().GetProperty("tagName").GetValue(obj);
list.Add(obj);
}
source to share
To create 10 objects MyClass
, you can do for example:
List<MyClass> list = new List<MyClass>();
for (int i = 0; i < 10; i++)
{
list.Add(new MyClass());
}
Although this is not "dynamic object creation", it is just instantiation.
For, you Dictionary
must specify a key and value. They can be of any type, not just int
(usually string
).
Dictionary<int, MyClass> dictionary = new Dictionary<int, MyClass>();
for (int i = 0; i < 10; i++)
{
dictionary.Add(i, new MyClass());
}
source to share
// Your class
public class OPCTag
{
public string tagName;
public string tagOvationMatch;
public string tagValue;
}
// Initialize a new OPCTag list object
List<OPCTag> lstTag = new List<OPCTag>();
for(int i = 0; i<10 ; i++)
{
lstTag.Add(new OPCTag());
}
// To read the value from the lstTag based on the index, here I am specifying the value index / first in the list.
var firstIndexTagname = lstTag[0].tagName;
var firstIndexTagOvationMatch = lstTag[0].tagOvationMatch;
var firstIndexTagValue = lstTag[0].tagValue;
source to share