Get value of a specific object property in C# without knowing the class behindC# get a value from a returned json objecthow to access an object which made with a function in c#Hidden Features of C#?How do you give a C# Auto-Property a default value?Deep cloning objectsHow do I get a consistent byte representation of strings in C# without manually specifying an encoding?LINQ's Distinct() on a particular propertyGet int value from enum in C#Get property value from string using reflection in C#What are the true benefits of ExpandoObject?How to Sort a List<T> by a property in the objectWhy not inherit from List<T>?
Why Isn’t SQL More Refactorable?
How did Shepard's and Grissom's speeds compare with orbital velocity?
Why doesn't WotC use established keywords on all new cards?
How can I close a gap between my fence and my neighbor's that's on his side of the property line?
How does this change to the opportunity attack rule impact combat?
How should I tell my manager I'm not paying for an optional after work event I'm not going to?
What matters more when it comes to book covers? Is it ‘professional quality’ or relevancy?
Why is Arya visibly scared in the library in S8E3?
BOOM! Perfect Clear for Mr. T
Can you complete the sequence?
Can my company stop me from working overtime?
What was the design of the Macintosh II's MMU replacement?
Why do money exchangers give different rates to different bills?
Expressing 'our' for objects belonging to our apartment
Point of the the Dothraki's attack in GoT S8E3?
Purpose of のは in this sentence?
I drew a randomly colored grid of points with tikz, how do I force it to remember the first grid from then on?
How to model the curly cable part of the phone
If I readied a spell with the trigger "When I take damage", do I have to make a constitution saving throw to avoid losing Concentration?
Why is the relative clause in the following sentence not directly after the noun and why is the verb not in the end of the sentence?
Does a card have a keyword if it has the same effect as said keyword?
What is the most remote airport from the center of the city it supposedly serves?
Why are prions in animal diets not destroyed by the digestive system?
On which topic did Indiana Jones write his doctoral thesis?
Get value of a specific object property in C# without knowing the class behind
C# get a value from a returned json objecthow to access an object which made with a function in c#Hidden Features of C#?How do you give a C# Auto-Property a default value?Deep cloning objectsHow do I get a consistent byte representation of strings in C# without manually specifying an encoding?LINQ's Distinct() on a particular propertyGet int value from enum in C#Get property value from string using reflection in C#What are the true benefits of ExpandoObject?How to Sort a List<T> by a property in the objectWhy not inherit from List<T>?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?
something like this:
object item = AnyFunction(....);
string value = item.name;
c# .net
add a comment |
I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?
something like this:
object item = AnyFunction(....);
string value = item.name;
c# .net
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
1
You can useSystem.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…
– JMK
Jul 9 '12 at 12:50
1
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51
add a comment |
I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?
something like this:
object item = AnyFunction(....);
string value = item.name;
c# .net
I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?
something like this:
object item = AnyFunction(....);
string value = item.name;
c# .net
c# .net
edited Jul 9 '12 at 12:53
uhu
asked Jul 9 '12 at 12:46
uhuuhu
83241224
83241224
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
1
You can useSystem.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…
– JMK
Jul 9 '12 at 12:50
1
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51
add a comment |
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
1
You can useSystem.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…
– JMK
Jul 9 '12 at 12:50
1
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
1
1
You can use
System.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…– JMK
Jul 9 '12 at 12:50
You can use
System.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…– JMK
Jul 9 '12 at 12:50
1
1
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51
add a comment |
6 Answers
6
active
oldest
votes
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
add a comment |
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
add a comment |
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
add a comment |
Reflection and dynamic value access are correct solutions to this question but are quite slow.
If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
add a comment |
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name=0 , Value=1", prop.Name, Functions.convertNullableToString(propertyValue)));
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
add a comment |
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same.
For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11395315%2fget-value-of-a-specific-object-property-in-c-sharp-without-knowing-the-class-beh%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
add a comment |
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
add a comment |
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
edited Jul 9 '12 at 12:55
answered Jul 9 '12 at 12:49
WaqarWaqar
1,8381215
1,8381215
add a comment |
add a comment |
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
add a comment |
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
add a comment |
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
edited Mar 22 at 22:18
answered Jul 9 '12 at 12:49
Eren ErsönmezEren Ersönmez
26.8k75682
26.8k75682
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
add a comment |
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
Can you please give a link for "dynamic". Thanks.
– Narendra
Jul 9 '12 at 13:18
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
@Rain link added
– Eren Ersönmez
Jul 9 '12 at 19:48
3
3
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
this should be the accepted answer
– Blair Holmes
Oct 24 '18 at 16:53
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
This should be the accepted answer.
– Human_AfterAll
Mar 30 at 13:52
add a comment |
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
add a comment |
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
add a comment |
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
answered Jul 9 '12 at 12:52
MaartenMaarten
19.1k33655
19.1k33655
add a comment |
add a comment |
Reflection and dynamic value access are correct solutions to this question but are quite slow.
If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
add a comment |
Reflection and dynamic value access are correct solutions to this question but are quite slow.
If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
add a comment |
Reflection and dynamic value access are correct solutions to this question but are quite slow.
If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
Reflection and dynamic value access are correct solutions to this question but are quite slow.
If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
answered Jul 9 '12 at 13:02
RafalRafal
9,8172347
9,8172347
add a comment |
add a comment |
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name=0 , Value=1", prop.Name, Functions.convertNullableToString(propertyValue)));
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
add a comment |
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name=0 , Value=1", prop.Name, Functions.convertNullableToString(propertyValue)));
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
add a comment |
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name=0 , Value=1", prop.Name, Functions.convertNullableToString(propertyValue)));
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
Simply try this for all properties of an object,
foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
var propertyName = prop.Name;
var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);
//Debug.Print(prop.Name);
//Debug.Print(Functions.convertNullableToString(propertyValue));
Debug.Print(string.Format("Property Name=0 , Value=1", prop.Name, Functions.convertNullableToString(propertyValue)));
NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.
edited Aug 29 '15 at 10:19
answered Aug 29 '15 at 10:10
Haseeb AhmedHaseeb Ahmed
5710
5710
add a comment |
add a comment |
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same.
For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
add a comment |
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same.
For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
add a comment |
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same.
For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same.
For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
answered Sep 28 '18 at 16:03
DughDugh
13113
13113
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11395315%2fget-value-of-a-specific-object-property-in-c-sharp-without-knowing-the-class-beh%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
GetValue(item, "PropertyName")
– Alex
Jul 9 '12 at 12:48
1
You can use
System.Reflection
to get the object type, and then create a new variable of this type, making it equal to item, and then access the property - switchonthecode.com/tutorials/…– JMK
Jul 9 '12 at 12:50
1
Do you control the AnyFunction? Why not use an interface here? And have AnyFunction return IHasName or something.
– Hammerstein
Jul 9 '12 at 12:51