I've been trying to experiment with reflection and I have a question.
Lets say I have a class, and in this class I have a property initilized with the new feature of c# 6.0
Class MyClass()
{
public string SomeProperty{ get; set; } = "SomeValue";
}
Is there any way of getting this value, with reflection, without initilizating the class?
I know I could do this;
var foo= new MyClass();
var value = foo.GetType().GetProperty("SomeProperty").GetValue(foo);
But what I want to do is something similiar to this ;
typeof(MyClass).GetProperty("SomeProperty").GetValue();
I know I could use a field to get the value. But it needs to be a property.
Thank you.
It's just a syntax sugar. This:
class MyClass()
{
public string SomeProperty{ get; set; } = "SomeValue";
}
will be unwrapped by compiler into this:
class MyClass()
{
public MyClass()
{
_someProperty = "SomeValue";
}
// actually, backing field name will be different,
// but it doesn't matter for this question
private string _someProperty;
public string SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; }
}
}
Reflection is about metadata. There are no any "SomeValue" stored in metatada. All you can do, is to read property value in regular way.
I know I could use a field to get the value
Without instantiating an object, you can get values of static fields only.
To get values of instance fields, you, obviously, need an instance of object.
Alternatively, if you need default value of property in reflection metadata, you can use Attributes, one of it from System.ComponentModel, do the work: DefaultValue. For example:
using System.ComponentModel;
class MyClass()
{
[DefaultValue("SomeValue")]
public string SomeProperty{ get; set; } = "SomeValue";
}
//
var propertyInfo = typeof(MyClass).GetProperty("SomeProperty");
var defaultValue = (DefaultValue)Attribute.GetCustomeAttribute(propertyInfo, typeof(DefaultValue));
var value = defaultValue.Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With