473,785 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1754
To do this you can either use reflection or System.Componen tModel, for
example:

PropertyDescrip torCollection props = TypeDescriptor. GetProperties(p er);
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.mic rosoft.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(str ing 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.Reflecti on;

namespace ConsoleApplicat ion1
{
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 propertyToRetri eve = "FirstName" ;

PropertyInfo propertyInfo =
personType.GetP roperty(propert yToRetrieve);

object retrievedValue = propertyInfo.Ge tValue(p, null);

Console.WriteLi ne("{0} = {1}", propertyToRetri eve,
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.Componen tModel, for
example:

PropertyDescrip torCollection props = TypeDescriptor. GetProperties(p er);
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.mic rosoft.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(str ing 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.Reflecti on;

namespace ConsoleApplicat ion1
{
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 propertyToRetri eve = "FirstName" ;

PropertyInfo propertyInfo =
personType.GetP roperty(propert yToRetrieve);

object retrievedValue = propertyInfo.Ge tValue(p, null);

Console.WriteLi ne("{0} = {1}", propertyToRetri eve,
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.Componen tModel 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.Componen tModel 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.Componen tModel 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.Componen tModel 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
3098
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 context.nextNode().selectNodes(expression);
8
13130
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
6806
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 understand it, xpath doesn't yet have regular expressions so I thought to do: function findNode (srch) { var node; var expr="//td"; var RE = new RegExp("\\s*" + srch + "\\s*$");
4
3584
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
2274
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) web server, so this is not a cross-site scripting attack. But I would prefer not to taint the target page with any extra logic to do this. (I will if I must.) The calling page has these elements:
2
1564
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
12347
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) end sub Well, of course it's posible, and can be done with some characters mannaging. This way you can complicate it as much as you want. The way i usualy do it is in 5 simple steps: 1. Create 2 string arrays, and save numbers in one and...
2
5086
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 evaluate that to a boolean which in this case would be True. Another example would be "(True or False) AND True" would be True. The reason for this is that I have a form where the user has to build some logic in a graphical interface. I can evaluate...
1
6547
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 static Stack operators = new Stack(); private static Stack operands = new Stack();
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.