473,385 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Is it possible to do dynamic property referencing in C#?

If so how?

Say you have a class like:

Expand|Select|Wrap|Line Numbers
  1. public class MyClass
  2. {
  3.   public double[] DataSet1;
  4.   public double[] DataSet2;
  5. }
  6.  
and i have a string called MyString that is "DataSet2".

Is it possible to somehow reference MyClass.DataSet2 dynamically by doing something like:

double[] MyOutput = MyClass.[MyString];


Thanks,
Jon
Nov 2 '07 #1
9 9658
Plater
7,872 Expert 4TB
Other then using a Dictionary or System.Reflection I'm not sure you can.
Nov 2 '07 #2
Should i be using some kind of string indexer instead?
Nov 2 '07 #3
Plater
7,872 Expert 4TB
Look at the NameValueCollection object, it should allow you supply a string for a name and store it with an object (any type of object)
Nov 2 '07 #4
r035198x
13,262 8TB
Look at the NameValueCollection object, it should allow you supply a string for a name and store it with an object (any type of object)
I don't know how you guys are communicating here but I don't even understand the first post. Is MyString a variable in MyClass which is static?
Nov 2 '07 #5
balabaster
797 Expert 512MB
I don't know how you guys are communicating here but I don't even understand the first post. Is MyString a variable in MyClass which is static?
We operate entirely telepathically ;)

The easiest way I can see of doing this is by using the Properties collection. Create a reference to the properties collection and add your properties into that. This way you can reference:

Msgbox(CType(Me.Properties("MyPropertyName"), Double)

Which I think in C# would be something like:
Expand|Select|Wrap|Line Numbers
  1. PropertyCollection MyProperties = new PropertyCollection();
  2. private void Form1_Load(object sender, EventArgs e){
  3.     MyProperties.Add("MyProperty1", null);
  4.     MyProperties.Add("MyProperty2", null);
  5.     MyProperties["MyProperty1"] = "Hello World";
  6.     MessageBox.Show((string)MyProperties["MyProperty1"]);
  7. }
I'm not sure if this is achievable at design-time though...the properties aren't normally added to a properties collection unless you specify that in the constructor of your class. This adds to code maintenance - if you add a property to your class, you have to remember to add it to the properties collection which should be read only so that other classes can't change it...so basically instead of just adding properties into your class in one place, you now need to remember to add them in two places...so yeah. There are lots of ways to achieve this - but I think this is likely the easiest...and if you look at the constructor of a form once you're done designing it, you'll see that it's the same kind of method used by microsoft with your controls collection using the IContainer. The plumbing is hidden away in the Form class that you inherit from, but it exposes a Controls collection that gives you the list of controls.
I think you could equally use the IContainer instead of the PropertyCollection - the effect is the same.
Nov 2 '07 #6
r035198x
13,262 8TB
It would be nice if the OP were to describe what they want to achieve.
I smell a simple design problem here.
Nov 3 '07 #7
JamieHowarth0
533 Expert 512MB
Hi guys,

I was just Googling around for a similar topic, not sure if anyone is still subscribed to this thread but I thought I'd just post this little gem I just found by searching for "dynamic properties class C#".
I will be making extensive use of this code in a desktop application I'm currently building which needs a base class and methods for serialising various objects and their properties into XML documents to be submitted to a web service so thought I'd share my tuppence (plus I'm then subscribed to this thread so I don't lose the link!).

codegecko
Dec 22 '09 #8
Frinavale
9,735 Expert Mod 8TB
You know, I think that the original question isn't about creating dynamic properties, but more along the lines of how to access the properties dynamically. It seems pretty straight forward that reflection is the key here.

For example (imports/using the System.Reflection namespace)
Expand|Select|Wrap|Line Numbers
  1.   Dim myString As String = "DataSet2"
  2.   Dim result() As Double = Nothing
  3.  
  4.   Dim mc As New MyClass 
  5.   Dim mcProperties() As PropertyInfo = GetType(MyClass).GetProperties
  6.  
  7.   Dim dataSet2Property As PropertyInfo = Array.Find(mcProperties, Function(x As PropertyInfo) String.Compare(x.Name, myString, True) = 0)  
  8.  
  9.   If dataSet2Property IsNot Nothing
  10.    result = dataSet2Property.GetValue(mc, BindingFlags.GetField, Nothing, Nothing, Nothing)
  11.   End If
  12.  
-Frinny
Dec 22 '09 #9
Plater
7,872 Expert 4TB
@codegecko
That was a very complex way of just using a Dictionary. WAY more work then you needed to do. And doesn't address the original issue.


And Frinny, you would post VBNET for a C# answer, lol

C#:(with less work :-P)
Expand|Select|Wrap|Line Numbers
  1. string myString="DataSet2";
  2. double result=null;
  3.  
  4. MyClass mc= new MyClass();
  5. System.Reflection.PropertyInfo dataSet2Property =MyClass.GetType().GetProperty(myString);
  6. if (dataSet2Property != null)
  7. {
  8.     result = dataSet2Property.GetValue(mc, System.Reflection.BindingFlags.GetField, null, null, null);
  9. }
  10.  
Dec 22 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Simon | last post by:
Am using the following code. <script language="JavaScript1.2"> function setquantity(productindex,productquantity) { //create the reference object irefname_none = eval("document." +...
25
by: jullag | last post by:
Hi, does anyone know of any javascript method that does the same job as document.write(), but not necessarily at the end of the document? For instance, insert some text inside an element that...
1
by: Nathan Bloomfield | last post by:
Does anyone know if there is any documentation which relates to Access2k + ? or can anyone help adjust the code? I am having trouble converting the DAO references. TITLE :INF: How to...
3
by: CAD Fiend | last post by:
Hello, Well, after an initial review of my database by my client, they have completely changed their minds about how they want their form. As a result, I'm having to re-think the whole process....
3
by: MikeY | last post by:
Hi Everyone, I am working in C#, windows forms.My question is this. All my button dynamic controls properties are present and accounted for except for the"FlatStyle" properties. I can't seem to...
2
by: Ron | last post by:
I need to write a custom textbox control that references an object located in the Global.asax class, but I can't compile the control into a DLL without including the reference to the project DLL...
8
by: Jerry Spence1 | last post by:
I am trying to create timers on demand by doing the following: Dim NewTimer As New System.Timers.Timer NewTimer.Interval = 10000 AddHandler NewTimer.Elapsed, AddressOf Timeup NewTimer.Enabled =...
6
by: YYZ | last post by:
In my program, a user can open up many different "Loans" -- each one is loaded into a dynamically created usercontrol (ucLoan) -- in order for them to be able to switch between the ones they have...
0
by: Javilen | last post by:
Hello, Maybe one of you can offer a possible solution to the problem I have below. The request to me is to build a dynamically populating dropdown list from a text box.(something similar to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.