473,387 Members | 1,669 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,387 software developers and data experts.

evaluate a string to an object question

I have a custom business object of type Person.

i created a page with check boxes that will post to a second page that is
strongly typed with the first page and i have a function that retreives all
the checked boxes from the first page. The ID value of each checkbox is the
name of a property in the business object (Name, Address, Phone, ...). I can
get all the ids no problem here.

Question is there a way to convert or evaluate a string value to get an the
object property? ... So that:
Person PER = new Person(); // use default consrtructor here
string str = PER + ".Name"; will give me PER.Name?
Thanks
--
(i''ll be asking a lot of these, but I find C# totally way cooler than vb
and there''s no go''n back!!!)
thanks (as always)

kes
Jun 27 '08 #1
8 1732
To do this you can either use reflection or System.ComponentModel, for
example:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(per);
string name = (string) props["Name"].GetValue(per);
int age = (int)props["Age"].GetValue(per);

etc

For more complex data there are a lot more things you can do...

Marc
Jun 27 '08 #2
On Thu, 22 May 2008 06:05:00 -0700, WebBuilder451
<We***********@discussions.microsoft.comwrote:
>I have a custom business object of type Person.

i created a page with check boxes that will post to a second page that is
strongly typed with the first page and i have a function that retreives all
the checked boxes from the first page. The ID value of each checkbox is the
name of a property in the business object (Name, Address, Phone, ...). I can
get all the ids no problem here.

Question is there a way to convert or evaluate a string value to get an the
object property? ... So that:
Person PER = new Person(); // use default consrtructor here
string str = PER + ".Name"; will give me PER.Name?
This is called reflection. First, you will need to get an object of
type "Type" that describes the class Person - this is done using
typeof(Person).

Then, use the GetProperty(string propertyName) method of the type
object to retrieve a PropertyInfo class by name.

Finally, use the GetValue method of the PropertyInfo class to get the
value for a given instance of "Person".

Since this is rather abstract, here is a concrete example that will
(hopefully) make things clearer:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.FirstName = "Anders";
p.LastName = "Hjelsberg";

Type personType = typeof(Person);
string propertyToRetrieve = "FirstName";

PropertyInfo propertyInfo =
personType.GetProperty(propertyToRetrieve);

object retrievedValue = propertyInfo.GetValue(p, null);

Console.WriteLine("{0} = {1}", propertyToRetrieve,
retrievedValue);

Console.ReadKey();
}

}
}

Regards,
Gilles.

Jun 27 '08 #3
Very Much appreciated!!
--
(i''ll be asking a lot of these, but I find C# totally way cooler than vb
and there''s no go''n back!!!)
thanks (as always)

kes
"Marc Gravell" wrote:
To do this you can either use reflection or System.ComponentModel, for
example:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(per);
string name = (string) props["Name"].GetValue(per);
int age = (int)props["Age"].GetValue(per);

etc

For more complex data there are a lot more things you can do...

Marc
Jun 27 '08 #4
WebBuilder451 wrote:
I have a custom business object of type Person.

i created a page with check boxes that will post to a second page that is
strongly typed with the first page and i have a function that retreives all
the checked boxes from the first page. The ID value of each checkbox is the
name of a property in the business object (Name, Address, Phone, ...). I can
get all the ids no problem here.

Question is there a way to convert or evaluate a string value to get an the
object property? ... So that:
Person PER = new Person(); // use default consrtructor here
string str = PER + ".Name"; will give me PER.Name?
Maybe make your business object also a Dictionary, so you could expose business
properties, but also expose the index itself the way AppSettings are done?

Person PER = new Person();
string str = PER["Name"];

And in Person you have the name property like:
public string Name
{
get { return this["Name"]; }
set { this["Name"] = value; }
}

Saves you reflection, though I'm unsure of how performant/a good idea it is. If
AppSettings uses it though, it can't be too too horrible. :P

Chris.
Jun 27 '08 #5
Thank you it does make it very clear. Your help is also very appreciated!!

KES
--
(i''ll be asking a lot of these, but I find C# totally way cooler than vb
and there''s no go''n back!!!)
thanks (as always)

kes
"Gilles Kohl [MVP]" wrote:
On Thu, 22 May 2008 06:05:00 -0700, WebBuilder451
<We***********@discussions.microsoft.comwrote:
I have a custom business object of type Person.

i created a page with check boxes that will post to a second page that is
strongly typed with the first page and i have a function that retreives all
the checked boxes from the first page. The ID value of each checkbox is the
name of a property in the business object (Name, Address, Phone, ...). I can
get all the ids no problem here.

Question is there a way to convert or evaluate a string value to get an the
object property? ... So that:
Person PER = new Person(); // use default consrtructor here
string str = PER + ".Name"; will give me PER.Name?

This is called reflection. First, you will need to get an object of
type "Type" that describes the class Person - this is done using
typeof(Person).

Then, use the GetProperty(string propertyName) method of the type
object to retrieve a PropertyInfo class by name.

Finally, use the GetValue method of the PropertyInfo class to get the
value for a given instance of "Person".

Since this is rather abstract, here is a concrete example that will
(hopefully) make things clearer:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.FirstName = "Anders";
p.LastName = "Hjelsberg";

Type personType = typeof(Person);
string propertyToRetrieve = "FirstName";

PropertyInfo propertyInfo =
personType.GetProperty(propertyToRetrieve);

object retrievedValue = propertyInfo.GetValue(p, null);

Console.WriteLine("{0} = {1}", propertyToRetrieve,
retrievedValue);

Console.ReadKey();
}

}
}

Regards,
Gilles.

Jun 27 '08 #6
The main issue with this type of approach is that you end up duplicating
everything - i.e. you have already declared various properties, but you
need to remember to add them into the indexer (or perhaps use reflection
in the default). Makes a bit of work, and note that the
System.ComponentModel approach I posted earlier is what most
data-binding uses under-the-hood, so it provides consistency.

In the case of AppSettings, there are no pre-defined values - it is
essentially a runtiome dictionary, so the indexer approach makes perfect
sense. The indexer also forces you to share a return type (although I
guess object would suffice).

Re your point on performance; by *default* yes, reflection and
System.ComponentModel are much slower than direct access, but if you are
going to be doing lots of this (i.e. bulk exports, etc), then with a few
tricks you can get the performance back up. Fortunately I've already
done those tricks ;-p
http://www.codeproject.com/KB/cs/Hyp...escriptor.aspx

Marc
Jun 27 '08 #7
Marc Gravell wrote:
The main issue with this type of approach is that you end up duplicating
everything - i.e. you have already declared various properties, but you
need to remember to add them into the indexer (or perhaps use reflection
in the default). Makes a bit of work, and note that the
System.ComponentModel approach I posted earlier is what most
data-binding uses under-the-hood, so it provides consistency.
Yeah, it is a downside, although the reflection-on-construction idea could
potentially provide better speed than reflection-on-access depending on number
of objects vs number of accesses.
In the case of AppSettings, there are no pre-defined values - it is
essentially a runtiome dictionary, so the indexer approach makes perfect
sense. The indexer also forces you to share a return type (although I
guess object would suffice).
Yeah, boxing all the return data to object could also introduce minor overhead
(something I hadn't considered).
Re your point on performance; by *default* yes, reflection and
System.ComponentModel are much slower than direct access, but if you are
going to be doing lots of this (i.e. bulk exports, etc), then with a few
tricks you can get the performance back up. Fortunately I've already
done those tricks ;-p
http://www.codeproject.com/KB/cs/Hyp...escriptor.aspx
See, I forgot to add the *other* option was to just wait for Marc to post the
"real" solution. :P

That's actually pretty impressive performance.
Chris.
Jun 27 '08 #8
What can I say... I like meta-programming ;-p

Marc
Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: David Laub | last post by:
I have no problems running the following dynamic XPath evaluator form MSXSL: <msxsl:script implements-prefix="dyn" language="jscript"> evaluate(context, expression) { return...
8
by: No Such Luck | last post by:
Is there anyway to literally evaluate the contents of a string in an if statement? For example: int i = 0; char * str = "i == 0"; if(str) /* I know this doesn't do what I want */ {
5
by: Csaba Gabor | last post by:
In Firefox 1.5 (this question is Mozilla specific as I am using greasemonkey) I would like to be able to use document.evaluate to return the first TD entry that shows ^\s*MySearchText\s*$. As I...
4
by: netnet | last post by:
Is it possible to evaluate a string as a method name? Something like this: Session = "loadFormFormACompany"; This is what I would like to do.... eval(Session+"()") Anyone have any ideas?
15
by: Phlip | last post by:
Javascripters: I have an outer page and an inner iframe. The outer page calculates some javascript, and wants the inner frame to run it. The inner frame should hit a page on the same (private)...
2
by: conzett | last post by:
I have the name of an object in the form of a string. Is there a way to access it as an object without eval? basically can I do this: function foo(){ this.bar = function(){ alert("test") } }
2
kadghar
by: kadghar | last post by:
Many people asks if there is a way to write a mathematical expression, writen as a string in a text box, so they can do something like: sub something_click() textbox2.text=eval(textbox1.text)...
2
by: yarborg | last post by:
This is kind of a weird one and hard to find answers online because of the format of the question. Essentially I want to be able to have a string that looks like this "True AND True AND True" and...
1
by: aitia | last post by:
this the code. i used ECLIPSE to run this.. it has some codes smells that i can't seem to figure out.. can any one help? import java.io.*; import java.util.*; public class Postfix { private...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: 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
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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.