runtime eval of an int variable name in string to the int value in the running code

G. Gunn - fs 146 Reputation points

suppose I have a struct of constants like

public struct myTableCols { public const int col1=0, col2=1,col3=3,...;}

and in the edit panel of controls filled with the value of column of selected row,

for each of those controls has the tag set to like

col1Tbx.Tag = "myTableCols.col1"

is there a way to

int colNbr = eval(col1Tbx.Tag);


I'm using .net 4.7.2 in a windows form app

PS I know I can set the tag with actual int value but that makes the code difficult to change when the table columns are changed

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,600 questions
No comments
{count} votes

Accepted answer
  1. Viorel 89,136 Reputation points

    Check an example:

    public struct myTableCols { public const int col1 = 0, col2 = 1, col3 = 3; };
    . . .
    string tag = "myTableCols.col2";
    string c = tag.Split( '.' )[1];
    int colNbr = (int)typeof( myTableCols ).GetField( c ).GetValue( null );
    1 person found this answer helpful.
    No comments

1 additional answer

Sort by: Oldest
  1. Timon Yang-MSFT 9,516 Reputation points

    Can we use enums or static classes instead of struct?

        public enum myEnum   
            col1 = 0, col2 = 1, col3 = 3  
        public static class myTableCols   
            public const int col1 = 0, col2 = 1, col3 = 3;   
        textBox1.Tag = myEnum.col1;  
        textBox1.Tag = myTableCols.col2;  

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.