question

GGunnfs-5814 avatar image
0 Votes"
GGunnfs-5814 asked GGunnfs-5814 edited

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

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







dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
1 Vote"
Viorel-1 answered Viorel-1 edited

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


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered GGunnfs-5814 edited

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I used to use enum but it's hassle having to cast to int:

textBox1.Text = myTable.ItermArray[(int) myEnum.col1].ToString();
...etc.

I have even try enum:int{..} but still required casting to int at lease in switch statement


as for static class, I don't see much advantage rather then make a function to eval the tag as int. struct allows that too.

0 Votes 0 ·