473,597 Members | 2,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Setting properties by name

Hello

I would like to write a method that allows me to pass a reference to an instance
of a class, the name of a property of that class and a value to set that
property to, the method would then set the property of the instance to the value

here is an example of what the method might look like

public void SetProperty(obj ect instance, string property, object value)
{
//TODO: set the named property of the instance with the value
}

The method could be called like this

SetProperty(myC lassInstance, "MyProperty ", "My Value");

How would such a method be written? how do you access the members of an instance
in a late bound manner, or is it even possible to pass a reference to the actual
property like so

SetProperty(myC lassInstance, myClassInstance .MyProperty, "The Value");

Where the method is not taking the value of myClassInstance .MyProperty but the
reference to the actual property so that it can set its value, is this possible?

Thanks

Alex
Feb 10 '06 #1
11 3481
Reflection:

instance.GetTyp e().GetProperty (property).SetV alue(instance, value, null);

(assumes public, writeable, instance property)

Marc
Feb 10 '06 #2
Alexander,

Look at the .net reflection.

The code for setting the property would look something like this:

Type t = myClassInstance .GetType();
PropertyInfo pi = t.GetProperty(M yProperty);
pi.SetValue(myC lassInstance, myValue, null);

Type.GetPropert y method has more than one overload. You may need to use some
of the others depending on the visibility of the property.

If you want to pass "instance of a property" you can use the PropertyInfo
class.

--
HTH
Stoitcho Goutsev (100)

"Alexander Walker" <al**@noemail.n oemail> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
Hello

I would like to write a method that allows me to pass a reference to an
instance
of a class, the name of a property of that class and a value to set that
property to, the method would then set the property of the instance to the
value

here is an example of what the method might look like

public void SetProperty(obj ect instance, string property, object value)
{
//TODO: set the named property of the instance with the value
}

The method could be called like this

SetProperty(myC lassInstance, "MyProperty ", "My Value");

How would such a method be written? how do you access the members of an
instance
in a late bound manner, or is it even possible to pass a reference to the
actual
property like so

SetProperty(myC lassInstance, myClassInstance .MyProperty, "The Value");

Where the method is not taking the value of myClassInstance .MyProperty but
the
reference to the actual property so that it can set its value, is this
possible?

Thanks

Alex

Feb 10 '06 #3
Here are some methods I've been using to accomplish that (both Set and Get).
They're in VB.NET though so you'll have to translate them:

' Description:
' Calls the get method for a property on an object using reflection.
GetProperty
' searches the inheritance chain until it finds a match. All access
levels
' (private, public etc) are supported
' Parameters:
' name - Name of property to get
' object - Object on which to get the property value
' params - Optional parameters to the property
' Return value:
' The returned value of the property's get method
' Exceptions:
' MissingMemberEx ception - No property or get method matching the
specified name or parameters was found
' MissingMethodEx ception - No get method was found (property is
write-only)
Public Shared Function GetProperty(ByV al name As String, ByVal obj As
Object, ByVal ParamArray params() As Object) As Object
Dim objectType As Type = obj.GetType
Dim flags As BindingFlags = BindingFlags.In stance Or _
BindingFlags.St atic Or _
BindingFlags.No nPublic Or _
BindingFlags.Pu blic

Dim propertyInfo As PropertyInfo
Dim types(params.Le ngth - 1) As Type
Dim index As Integer
For index = 0 To params.Length - 1
types(index) = params(index).G etType
Next

While Not objectType Is Nothing
propertyInfo = objectType.GetP roperty(name, flags, Nothing, Nothing,
types, Nothing)
If propertyInfo Is Nothing Then
objectType = objectType.Base Type
Else
Exit While
End If
End While

If propertyInfo Is Nothing Then
Throw New MissingMemberEx ception(obj.Get Type.FullName, "")
ElseIf Not propertyInfo.Ca nRead Then
Throw New MissingMethodEx ception(obj.Get Type.FullName, "")
Else
Return propertyInfo.Ge tValue(obj, params)
End If
End Function

' Description:
' Calls the set method for a property on an object using reflection.
SetProperty
' searches the inheritance chain until it finds a match. All access
levels
' (private, public etc) are supported
' Parameters:
' name - Name of property to set
' object - Object on which to set the property value
' value - Value to assign to the property
' params - Optional parameters to the property
' Return value:
' None
' Exceptions:
' MissingMemberEx ception - No property matching the specified name or
parameters was found
' MissingMethodEx ception - No set method was found (property is
read-only)
Public Shared Sub SetProperty(ByV al name As String, ByVal obj As Object,
ByVal value As Object, ByVal ParamArray params() As Object)
Dim objectType As Type = obj.GetType
Dim flags As BindingFlags = BindingFlags.In stance Or _
BindingFlags.St atic Or _
BindingFlags.No nPublic Or _
BindingFlags.Pu blic

Dim propertyInfo As PropertyInfo
Dim types(params.Le ngth - 1) As Type
Dim index As Integer
For index = 0 To params.Length - 1
types(index) = params(index).G etType
Next

While Not objectType Is Nothing
propertyInfo = objectType.GetP roperty(name, flags, Nothing, Nothing,
types, Nothing)
If propertyInfo Is Nothing Then
objectType = objectType.Base Type
Else
Exit While
End If
End While

If propertyInfo Is Nothing Then
Throw New MissingMemberEx ception(obj.Get Type.FullName, "")
ElseIf Not propertyInfo.Ca nWrite Then
Throw New MissingMethodEx ception(obj.Get Type.FullName, "")
Else
propertyInfo.Se tValue(obj, value, params)
End If
End Sub
/claes

"Alexander Walker" <al**@noemail.n oemail> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
Hello

I would like to write a method that allows me to pass a reference to an
instance
of a class, the name of a property of that class and a value to set that
property to, the method would then set the property of the instance to the
value

here is an example of what the method might look like

public void SetProperty(obj ect instance, string property, object value)
{
//TODO: set the named property of the instance with the value
}

The method could be called like this

SetProperty(myC lassInstance, "MyProperty ", "My Value");

How would such a method be written? how do you access the members of an
instance
in a late bound manner, or is it even possible to pass a reference to the
actual
property like so

SetProperty(myC lassInstance, myClassInstance .MyProperty, "The Value");

Where the method is not taking the value of myClassInstance .MyProperty but
the
reference to the actual property so that it can set its value, is this
possible?

Thanks

Alex

Feb 10 '06 #4
"Claes Bergefall" <cl************ *@nospam.nospam > schrieb:
Here are some methods I've been using to accomplish that (both Set and
Get). They're in VB.NET though so you'll have to translate them:


Mhm... You could use 'CallByName' in VB.NET instead of these methods ;-).

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 10 '06 #5
Here are the methods I came up with

delegate object GetPropertyCall back(object parent, object control,
string propertyName);
delegate void SetPropertyCall back(object parent, object control, string
propertyName, object value);

public object GetProperty(obj ect parent, object control, string
propertyName)
{
Control instance = null;
if (parent != null)
{
instance = (Control)parent ;
}
else
{
instance = (Control)contro l;
}
if (instance.Invok eRequired)
{
GetPropertyCall back d = new GetPropertyCall back(GetPropert y);
return instance.Invoke (d, new object[] { parent, control,
propertyName });
}
else
{
return
control.GetType ().GetProperty( propertyName).G etValue(control , null);
}
}

public void SetProperty(obj ect parent, object control, string
propertyName, object value)
{
Control instance = null;
if (parent != null)
{
instance = (Control)parent ;
}
else
{
instance = (Control)contro l;
}
if (instance.Invok eRequired)
{
SetPropertyCall back d = new SetPropertyCall back(SetPropert y);
instance.Invoke (d, new object[] { parent, control, propertyName,
value });
}
else
{
control.GetType ().GetProperty( propertyName).S etValue(control ,
value, null);
}
}

I needed a generic way of accessing control properties in a thread safe manner,
the reason for the parent and the control properties are for those cases where
the "control" that you are trying to access does not inherit from control and
does not have an InvokeRequired property, the particular situation I face
involved a progress bar on a status strip control, the progress bar didn't
inherit from control and so didn't have an InvokeRequired property, so I passed
the status strip as the parent

Thanks

Alex
Feb 11 '06 #6
Some observations:

Since you always expect parent and control to be Controls, why not specify
them as Control on the interface?

The "callback" isn't really what I would call a callback - normally this
involves an AsyncResult or somesuch; perhaps just call it
GetPropertyDele gate?

I can't recall (and don't have an IDE handy), but some of the Invoke methods
accept a params parameter which makes the call easier; and looks like they
should be static methods?

Other than that, it looks like it should work,

Marc
Feb 11 '06 #7
ammendment; I see what you mean about the child; if it must be that way, I'd
have 2 versions of each

public static object GetProperty(obj ect obj, string propertyName) {
return GetProperty(obj as Control, obj, propertyName);
}

public static object GetProperty(Con trol parent, object obj, string
propertyName) {
if(parent==null || !parent.InvokeR equired) {
// call directly
}
else {
// invoke (private) delegate
}
}

===

Done this way, I can pass any object to the first version of GetProperty; if
it is a control it will be automatically passed to the right thread; if I
know I have an object that needs to be accessed on a particular thread I can
use the second version. You could consider replacing Control with
ISynchronizeInv oke, but that is probably overkill.

Marc
Feb 11 '06 #8
Hmm, guess I could. Didn't know about that one :-)
Does it work with private members as well?

/claes
"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:uq******** ******@TK2MSFTN GP09.phx.gbl...
"Claes Bergefall" <cl************ *@nospam.nospam > schrieb:
Here are some methods I've been using to accomplish that (both Set and
Get). They're in VB.NET though so you'll have to translate them:


Mhm... You could use 'CallByName' in VB.NET instead of these methods ;-).

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Feb 13 '06 #9
Hi Alexander,

I just want to check how things are going and whether or not your problem
has been resolved. If there is any question, please feel free to join the
community and we are here to support you at your convenience. Thanks again!

Best Regards,

Terry Fei[MSFT]
Microsoft Community Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

--------------------
From: "Alexander Walker" <al**@noemail.n oemail>
Subject: Setting properties by name
Date: Fri, 10 Feb 2006 13:58:27 -0000
Lines: 31
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.2670
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2670
Message-ID: <##************ **@TK2MSFTNGP09 .phx.gbl>
Newsgroups: microsoft.publi c.dotnet.framew ork.windowsform s,microsoft.pub lic.dotnet.lang u
ages.csharpNNTP-Posting-Host: 213-208-113-136.dyn.gotadsl .co.uk 213.208.113.136
Path: TK2MSFTNGXA01.p hx.gbl!TK2MSFTN GP08.phx.gbl!TK 2MSFTNGP09.phx. gbl
Xref: TK2MSFTNGXA01.p hx.gbl microsoft.publi c.dotnet.langua ges.csharp:3850 54
microsoft.publi c.dotnet.framew ork.windowsform s:94079X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.csharp

Hello

I would like to write a method that allows me to pass a reference to an instanceof a class, the name of a property of that class and a value to set that
property to, the method would then set the property of the instance to the value
here is an example of what the method might look like

public void SetProperty(obj ect instance, string property, object value)
{
//TODO: set the named property of the instance with the value
}

The method could be called like this

SetProperty(my ClassInstance, "MyProperty ", "My Value");

How would such a method be written? how do you access the members of an instancein a late bound manner, or is it even possible to pass a reference to the actualproperty like so

SetProperty(my ClassInstance, myClassInstance .MyProperty, "The Value");

Where the method is not taking the value of myClassInstance .MyProperty but thereference to the actual property so that it can set its value, is this possible?
Thanks

Alex


Feb 15 '06 #10

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

Similar topics

1
2530
by: John Marble | last post by:
I looked around for a way to change the format and the decimal setting of a REAL type variable, but I can't seem to be able to find the synthax anywhere. Here is an exemple of what I am doing: ALTER TABLE MAIN ALTER COLUMN sup_visee REAL; It works, it changes the column "sup_visee" which was a String into a REAL. What I want to do too is to be able to set the REAL format to
18
18341
by: Dixie | last post by:
Can I set the Format property in a date/time field in code? Can I set the Input Mask in a date/time field in code? Can I set the Format of a Yes/No field to Checkbox in code? I am working on a remote update of tables and fields and can't find enough information on these things. Also, how do you index a field in code?
1
2645
by: Danko Greiner | last post by:
Thanx Willy, this was very helpful. But i also need (and want to know) how to do this from code. Can you plase give me right topic in MSDN? is there good example? Thanx p.s. this is copy/paste from previous thread, don't ask why... "Grei" <danko.greinerREMOVE@zg.htnet.hr> wrote in message news:d1vihg$m3b$1@ss405.t-com.hr...
1
2368
by: Rob Meade | last post by:
Hi all, I have a loop in my code which builds the controls on the page. I at one stage need to add some hidden input controls dynamically, I have achieved this, and I have set their properties, however, there seems to be one that I cannot set - ie, Name.. My code looks like this:
0
7915
by: Johan | last post by:
Hi I'm using WMI to set and remove folderpermissions and it sems to work fine, sometimes. I start by having the folderpermissons manuly set to Everyone and Everone has full rights. When I'm setting and removing permissons on a mapped folder in the network it works fine but when doing the same thing on a folder om my harddrive Everyone does not get removed. Does anyone have any idea how to fix this or how to set and remove...
3
2576
by: John Dann | last post by:
I'm getting forgetful - can someone please remind me where I can edit the 'Manufacturer' setting in VB.Net 2003 Pro, ie the string that's used for the default outer folder name during the standard deployment process? Thanks JGD
7
1998
by: Ronald S. Cook | last post by:
In a .NET Windows app, if I set somehting like the title of the form to "MyApp" at run-time, will that make the app run slightly slower than if I had set the title at design-time? Thanks, Ron
6
11064
by: | last post by:
I have made some user controls with custom properties. I can set those properties on instances of my user controls, and I have programmed my user control to do useful visual things in response to how those properties are set. I want to be able to do two other things: a) add User control instances to my page, filling in the place of placeholder controls, and b) programmatically setting custom properties on those dynamically spawned...
3
2441
by: Ryan Liu | last post by:
Hi, When i add a connection string FpConnStr from application setting UI in VS 2008, it ends with sth. like: <connectionStrings> <clear /> <add name="CapiInterviewer.Properties.Settings.FpConnStr" connectionString="data source=PowerCapiData" providerName="System.Data.SQLite" />
8
16089
by: Andrus | last post by:
..NET 2 Winforms application. How to create new setting and set it default value in userSettings section of app.config file or overwrite existing setting value ? I found code below in this list which modifies Application setting section but how to add new item to userSettings ? Andrus.
0
7977
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
7894
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
8276
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...
1
8044
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,...
1
5847
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
3893
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...
1
2409
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1496
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1245
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.