Mohsin Shoaib
Mohsin Shoaib

Reputation: 158

C# Use class properties as array

I have a View Mode class.

public class VM_MyClass
{
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "Date Of Birth")]
    public string DOB { get; set; }
}

I want to use its attributes like this:

VM_MyClass model = new VM_MyClass();
model[0] = "Alpha" // Name
model[1] = "11/11/14" // DOB

Is there any possibility?

Upvotes: 1

Views: 839

Answers (2)

Mohsin Shoaib
Mohsin Shoaib

Reputation: 158

@Georg Vovos, Thanks man for your answer, I also have solved it by this approach. As per my above comment I need to assign values of array to model attributes. So I found this way.

I am using your approach, which is more appropriate :) thanks for help.

    VM_MyClass model = new VM_MyClass();

    var ClassProperties = model.GetType().GetProperties();

    int counter = 0;
    foreach (var item in col)
    {
        Type type = model.GetType();

        System.Reflection.PropertyInfo propertyInfo = type.GetProperty(ClassProperties[counter].Name);

        propertyInfo.SetValue(model, item.InnerText);

        counter++;
    }

Upvotes: 0

George Vovos
George Vovos

Reputation: 7618

You can use an indexer and the reflection API like in the following example
(As other have said you must be very careful)

public class VM_MyClass
{
    private static Type ThisType = typeof(VM_MyClass);
    public string Name { get; set; }

    public DateTime DOB { get; set; }

    public object this[string propertyName]
    {
        get
        {
            return GetValueUsingReflection(propertyName);
        }
        set
        {

            SetValueUsingReflection(propertyName, value);
        }
    }

    private void SetValueUsingReflection(string propertyName, object value)
    {
        PropertyInfo pinfo = ThisType.GetProperty(propertyName);
        pinfo.SetValue(this, value, null);
    }
    private object GetValueUsingReflection(string propertyName)
    {
        PropertyInfo pinfo = ThisType.GetProperty(propertyName);
        return pinfo.GetValue(this,null);
    }
}

You can use it like this:

using System;
using System.Reflection;
namespace Example
{
  class Program
  {
    static void Main(string[] args)
    {
        VM_MyClass model = new VM_MyClass();

        model["Name"] = "My name";
        model["DOB"] = DateTime.Today;

        Console.WriteLine(model.Name);
        Console.WriteLine(model.DOB);
        //OR
        Console.WriteLine(model["Name"]);
        Console.WriteLine(model["DOB"]);

        Console.ReadLine();
    }
  }
}

Upvotes: 2

Related Questions