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

G. Gunn - fs 146 Reputation points
2021-04-23T05:02:50.257+00:00

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

C#
C#
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,001 questions
No comments
{count} votes

Accepted answer
  1. Viorel 82,911 Reputation points
    2021-04-23T05:20:28.933+00:00

    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 );
    
    No comments

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,501 Reputation points
    2021-04-23T08:56:46.98+00:00

    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.