FPGA
FPGA

Reputation: 3865

Looping through properties in the constructor

Is there a way to select all properties of a specific type and give it a default value from inside the constructor?

I have 32 int32 properties with backing fields in a class, and i want to default all of them to -1 in the constructor, any other way than writing them all in the constructor?

Upvotes: 1

Views: 2281

Answers (2)

spender
spender

Reputation: 120450

Might take a bit of refinement, but something like this would do the trick.

class A{
    public A()
    {
        var props = this.GetType()
                .GetProperties()
                .Where(prop => prop.PropertyType == typeof(int));
        foreach(var prop in props)
        {
            //prop.SetValue(this, -1);  //.net 4.5
            prop.SetValue(this, -1, null); //all versions of .net
        }
    }
    public int ValA{get; set;}
    public int ValB{get; set;}
    public int ValC{get; set;}
}

Upvotes: 3

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

IF you want to do this:

void Main()
{
    var test = new Test();
    Console.WriteLine (test.X);
    Console.WriteLine (test.Y);
}

Class Definition:

 public class Test 
 {
       public int X {get; set;}
       public int Y {get; set;}

       public Test()
       {
              foreach(var prop in this.GetType().GetProperties())
              {
                    if(prop.PropertyType == typeof(int))
                    {
                          prop.SetValue(this, -1);
                    }
              }
       }
 }

Output:

-1
-1

Upvotes: 1

Related Questions