Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# 6.0 and reflection, getting value of Property Initializers

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.

like image 788
Rudithus Avatar asked Oct 28 '15 06:10

Rudithus


2 Answers

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.

like image 135
Dennis Avatar answered Oct 22 '22 01:10

Dennis


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;
like image 42
Alexander Vasilyev Avatar answered Oct 22 '22 01:10

Alexander Vasilyev