0

I want to check specific fields of a class for content. If there is no value, it should give a message. The current example is working. But I am looking for a way to to the same without Reflection.

using System;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
       static void Main(string[] args)
       {
           TableDescription table1 = new TableDescription { BUYER_AID = 0, DESCRIPTION_LONG = 3, EAN = 2, SUPPLIER = 17};
           TableDescription table2 = new TableDescription();
           string [] members = new string[] { "BUYER_AID", "DESCRIPTION_LONG", "EAN" };
           CheckAndSetValue(table1, table2, members);
       }

       static void CheckAndSetValue(TableDescription t1, TableDescription t2, string[] list)
       {
           foreach (string name in list)
           {
               Type type = typeof(TableDescription);
               FieldInfo typeinfo = type.GetField(name);
               short value = Convert.ToInt16(typeinfo.GetValue(t1));
               if (0 != value)
               {
                   typeinfo.SetValue(t2, value);
               }
               else
               { 
                    Console.WriteLine($"Value for {name} is missing!");
               }
           }
       }
   }
   public class TableDescription
   {
       public short BUYER_AID = 0;
       public short DESCRIPTION_LONG = 0;
       public short EAN = 0;
       public short SUPPLIER = 0;
   }
}

Is there a way to to it something like:

var[] members = new var[]{TableDescription.BUYER_AID, TableDescription.DESCRIPTION_LONG, TableDescription.EAN};

I am looking for a solution to work without stings. Working with Strings will make trouble with refactoring and on error it will crash during runtime.

  • You can always use `nameof()` to avoid your refactoring concerns. (not that I'm suggesting to use such code) – pinkfloydx33 Mar 14 '21 at 10:59
  • Using `nameof()` just solves the refactoring. It uses still Strings. The other way seams to use unsafe Code like [in this question](https://stackoverflow.com/questions/30817924/obtain-non-explicit-field-offset). – user3210577 Mar 15 '21 at 07:24
  • You could use Expressions which is technically reflection but could be built in a clean way. . But unless your fields/properties are alway of single type (short in your example) then it gets messy – pinkfloydx33 Mar 15 '21 at 08:02
  • if you have access to TableDescription: you could flag every member with an attribute, then via reflection detect all of it's fields that are flagged with the attribute and validate it. – Soraphis Jan 16 '23 at 12:14

0 Answers0