0

So, I need to retrieve all properties of an instance which currently have a value that matches the default value of their respective type. Something along the lines of

GetType().GetProperties().Where(x => 
    x.GetValue(this).Equals(default(x.PropertyType)));

This obviously doesn't work because it seems 'x' cannot be resolved anymore at this point. What could I do?

xvdiff
  • 2,179
  • 2
  • 24
  • 47
  • 1
    No, that's not the problem. The immediate problem is that `default` expects a type, not a value, not even a value of type `System.Type`. That's far from the only problem, though. –  Sep 23 '14 at 11:18
  • @hvd Care to explain what you mean by 'the only problem'? – xvdiff Sep 23 '14 at 12:04
  • 1
    One other problem is that if a property of reference type or nullable value type is `null` (the default value of the type), then `x.GetValue(this).Equals(whatever)` will throw a `NullReferenceException`. Another problem is that `x.GetValue(this)` will throw an exception if you have any indexers. –  Sep 23 '14 at 12:31
  • @hvd Oh dear. Well, a NullReferenceException can easily be avoided, but how to overcome the indexers problem? Binding flags on GetProperties()? – xvdiff Sep 23 '14 at 12:46
  • 1
    For that problem, I think you should be able to check `!x.GetIndexParameters().Any()`, but I'm not completely certain. –  Sep 23 '14 at 12:48
  • @hvd Other answers on SO also suggest GetIndexParameters(). Will definitely test this, but it seems to be the right way. Also upboats for your help. Thank you. – xvdiff Sep 23 '14 at 12:54
  • Basically I would do something like this: `GetType().GetProperties().Where(x => Object.Equals(x.GetValue(this, null), Activator.CreateInstance(x.PropertyType)))`. It has some border cases for indexed properties, but handles the "common cases". – flindeberg Sep 29 '14 at 11:56

1 Answers1

0

The problem is slightly different. You cannot pass a runtime instance of Type to default. Your problem can be simplified to this:

var type = typeof (string);
var defaultValue = default(type); // doesn't work

That doesn't work. Instead, you want to get the default value at run time, which has been answered by this question.

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286