Question Assigning a value to a variable through variable name

Bryan_James

Member
Joined
Jul 6, 2016
Messages
5
Location
Philippines
Programming Experience
1-3
Hi! I am trying to create my own ORM. Database fields will be the same name as the class variables of the model. Now, I searched for a way to get column name in SqlDataReader in C#. In my code, "ListAllVars()" lists the variables in C#:

C#:
    public interface IBaseModel
    {
        void ListAllVars();
    }

    public class BaseModel : IBaseModel
    {
        protected string tableName = "old table name";
        protected string timestamp = "some stamp";
        
        public void ListAllVars()
        {
            BindingFlags bindingFlags = BindingFlags.Public |
                            BindingFlags.NonPublic |
                            BindingFlags.Instance |
                            BindingFlags.Static;

            foreach (FieldInfo field in this.GetType().GetFields(bindingFlags))
            {
                Console.WriteLine(field.Name);
            }
        }
    }

    public interface IModel : IBaseModel
    {
        int IntegerMember { get; set; }
        string StringMember { get; set; }
        string ModelName { get; set; }

        void PrintHello();
    }

    public class Model : BaseModel, IModel
    {
        private int integerMember;
        private string stringMember;
        private string modelName;
        private string tableName = "new table name";

        public int IntegerMember
        {
            get => this.integerMember;
            set => this.integerMember = value;
        }

        public string StringMember
        {
            get => this.stringMember;
            set => this.stringMember = value;
        }

        public string ModelName
        {
            get => this.modelName;
            set => this.modelName = value;
        }
    }

Now that I have variable names of the class and column names of a table, I want to assign a value to a variable in a class through the column name (which is also a string). Like so:

C#:
int userID = 0;
string fieldName = "userID";
string fieldValue = "18";

_some_function_or_method(fieldValue).value(Convert.ToInt32(fieldValue));
Console.WriteLine("User ID value: " + userID);
// outputs "User ID value: 18"

Is there any way to achieve it?
 
Use reflection: use GetField and SetValue methods

You can use reflection.

The following code should point you in the right direction.

C#:
    public class User
    {
        public int UserId;
    }


    public class Program
    {
        public static void Main()
        {
            var user = new User();


            SetIntField(user, "UserId", "18");


            Console.WriteLine(user.UserId); // Print 18
        }


        public static void SetIntField<T>(T obj, string fieldName, string fieldValue)
        {
            obj.GetType().GetField(fieldName).SetValue(obj, Convert.ToInt32(fieldValue));
        }
    }
 
Back
Top Bottom