Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign values to object properties dynamically

Tags:

c#

.net

I have an object with properties ct1 - ct5. The object is an auto-generated linq-to-sql object. I would like to assign values to these properties in c#. Is there any way to do this in a for loop?

e.g. something like (object name: new_condition):

for (int i = 1; tag <= 5; i++)
{
   new_condition.cti = values[i];
}

where the i in cti gets evaluated.

Thanks in advance

like image 870
bob Avatar asked Aug 08 '26 22:08

bob


1 Answers

You can do it using reflection. For instance, supose you have a class A like this:

class A
{
    public int P1 { get; set; }
    public int P2 { get; set; }
    public int P3 { get; set; }
}

You can do it like in this simple console sample:

static void Main(string[] args)
{
    var a = new A();
    foreach (var i in Enumerable.Range(1,3))
    {
        a.GetType().GetProperty("P" + i).SetValue(a, i, null);
    }
    Console.WriteLine("P1 = {0}",a.P1);
    Console.WriteLine("P2 = {0}",a.P2);
    Console.WriteLine("P3 = {0}",a.P3);
    Console.ReadLine();
}

The output will be:

P1 = 1
P2 = 2
P3 = 3
like image 100
Raúl Otaño Avatar answered Aug 10 '26 11:08

Raúl Otaño



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!