0

Here is sample code

public class Foo
{
    public string Data { get; set; } = "Example";
}

how can I get the default value "Example" of property Data from typeof(Foo)? we don't instance the class, don't change class.

there are thousands of all classes, which are from another engineering team, we cannot do any change to those code.

I tried to find a solution from this post: C# Get property value without creating instance? but no luck.

From above post,

  • By Jon Skeet's answer, it throw exception at ugly() or openDelegate(null), see the screenshot;
  • By Jordão's answer, it need attribute;
  • By Jon Senchyna & alexm's answer, it need change property to static;

enter image description here Thanks.

Dongdong
  • 2,208
  • 19
  • 28
  • 1
    Can't you make some static file with default values and assign it's value as init in Foo.Data property? Also, the answer from link you provided works for me – sTrenat Jun 02 '20 at 16:44
  • Also, what's blocks you from creating an instance? Even if it's kind of dynamic type, you can probably use Activator.CreateInstance to create it and look up value, whatever the reason you need it is – sTrenat Jun 02 '20 at 16:47
  • @sTrenat this is a huge reflection process before DI framework starts working, so it's hard to instance them. – Dongdong Jun 02 '20 at 17:01
  • 1
    Duplicate of [C# Get property value without creating instance?](https://stackoverflow.com/questions/11162652/c-sharp-get-property-value-without-creating-instance). If you feel it is not, [edit] your question with how you tried to use the answers to that question, and how they did not work. – Heretic Monkey Jun 02 '20 at 17:20
  • @HereticMonkey question updated. I am serious to ask this question, it does block me. Thanks. – Dongdong Jun 02 '20 at 17:42
  • There are actually two different techniques outlined in Jon Skeet's answer. Both of which he implores people not to use. The others indeed mention using different techniques, because **you cannot get an instance property's value without an instance of the class**. Asking the question again does not change that fact, nor will it magically create new answers. If you want to draw attention to the existing question to try and drum up new answers, [add a bounty to that existing question](https://stackoverflow.com/help/bounty). – Heretic Monkey Jun 02 '20 at 17:48
  • @HereticMonkey thanks, question updated again, attached the issue for Jon Skeet's answer. I can only add bounty in 2 days. I will. Thanks. – Dongdong Jun 02 '20 at 17:58
  • I think the only way would be to deconstruct constructor instructions, since auto property initialization is part of constructor only, which fills backingField of your property during object inicialization – sTrenat Jun 03 '20 at 06:28

0 Answers0