Dynamic Field in C#?

  • Thread starter Thread starter Hoi Wong
  • Start date Start date
H

Hoi Wong

In new versions of MATLAB, I can do dynamic field like

userdata.('username').electrocardiogram = 4,

where 'username' can be replaced by any string variable. This made my
software design much neater. Does anybody know if C# support that? If so,
what's the syntax?

Thanks in advance.

Cheers,
Hoi
 
Hoi Wong said:
In new versions of MATLAB, I can do dynamic field like

userdata.('username').electrocardiogram = 4,

where 'username' can be replaced by any string variable. This made my
software design much neater. Does anybody know if C# support that? If so,
what's the syntax?

You need to use a Dictionary<TKey,TValue>:

userData["username"].Electrocardiogram = 4;

(where userData is defined appropriately, of course).
 
Hoi Wong said:
In new versions of MATLAB, I can do dynamic field like

userdata.('username').electrocardiogram = 4,

where 'username' can be replaced by any string variable. This made my
software design much neater. Does anybody know if C# support that? If so,
what's the syntax?

I know you can do this with ADO.Net and C# when addressing fields in a
datatable dynamically addressing fields in the table by name. As a matter of
fact, I was taking a column/field name from a another table that
represented the fieldname in the table I wanted to access.

This just off the top of my head as to how it worked.

string fieldname = arow[brow["displayfldname"].Tostring()];

The field in arow was accessed via the name of the field that was in brow --
"displayname". Arow held the data that brow accessed to build dynamic
screens based on the tblScreenFields access into tblScreenData.

The ToString() was the key to getting it to work.

So, I don't see why you couldn't do the same in your example of addressing a
field dynamically, hopefully, and you can try it.
 
Sweet. Thanks for the pointer (no pun intended)!


Jon Skeet said:
Hoi Wong said:
In new versions of MATLAB, I can do dynamic field like

userdata.('username').electrocardiogram = 4,

where 'username' can be replaced by any string variable. This made my
software design much neater. Does anybody know if C# support that? If so,
what's the syntax?

You need to use a Dictionary<TKey,TValue>:

userData["username"].Electrocardiogram = 4;

(where userData is defined appropriately, of course).

--
Jon Skeet - <[email protected]>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top