Convert string to property name?
-
I have an object named 'dv' 'dv' has a string property named 'refNumber' There is also a string 'altString' = "refNumber" Is there a way to use 'altString' to get that property from 'dv'? string newString = dv.??altString?? -- should set newString the same as -- string newString = dv.refNumber Thanks for your suggestions.
-
I have an object named 'dv' 'dv' has a string property named 'refNumber' There is also a string 'altString' = "refNumber" Is there a way to use 'altString' to get that property from 'dv'? string newString = dv.??altString?? -- should set newString the same as -- string newString = dv.refNumber Thanks for your suggestions.
Reflection can do this. Use
System.Reflection
name space. You'd do something like (not tested)PropertyInfo property = (PropertyInfo) dv.GetMembers().SingleOrDefault(info =>
info.MemberType == MemberTypes.Property &&
info.Name == altString);
string newString = string.Empty;
if (property != null)
newString = (string) property.GetValue(dv, null);:)
Best wishes, Navaneeth
-
Reflection can do this. Use
System.Reflection
name space. You'd do something like (not tested)PropertyInfo property = (PropertyInfo) dv.GetMembers().SingleOrDefault(info =>
info.MemberType == MemberTypes.Property &&
info.Name == altString);
string newString = string.Empty;
if (property != null)
newString = (string) property.GetValue(dv, null);:)
Best wishes, Navaneeth
-
BDJones wrote:
but where does 'refNumber' occur in your reply? Quote Selected Text
You said it will be in
altString
variable. I am using that variable to compare against name. You can replace it with "refNumber" if you wish to.Best wishes, Navaneeth
-
I have an object named 'dv' 'dv' has a string property named 'refNumber' There is also a string 'altString' = "refNumber" Is there a way to use 'altString' to get that property from 'dv'? string newString = dv.??altString?? -- should set newString the same as -- string newString = dv.refNumber Thanks for your suggestions.
-
BDJones wrote:
but where does 'refNumber' occur in your reply? Quote Selected Text
You said it will be in
altString
variable. I am using that variable to compare against name. You can replace it with "refNumber" if you wish to.Best wishes, Navaneeth