Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if property exists [duplicate]

Tags:

c#

I'm trying to read properties from DirectoryEntry. Unfortunately not all records have employeeNumber property so I need to check if it exists. I already tried:

a == one DirectoryEntry record
a.GetType().GetProperty("employeeNumber")==null //always returns true
String.IsNullOrWhiteSpace(a.Properties["employeeNumber"].ToString()) //exception

what else can I try?

like image 411
szpic Avatar asked Jan 21 '26 15:01

szpic


2 Answers

You can try like this:

OBJECT.GetType().GetProperty("PROPERTY") != null

So in your code it would be like:

var a = one DirectoryEntry record;
var pi = a.GetType().GetProperty("employeeNumber");
var value = pi.GetValue(a, null);

EDIT:-

Try this:

bool x = a.Properties.Contains("employeeNumber");
like image 127
Rahul Tripathi Avatar answered Jan 24 '26 04:01

Rahul Tripathi


Something like this:

a.Properties["employeeNumber"] == null || a.Properties["employeeNumber"].ToString().Length == 0

In your case a.Properties["employeeNumber"] can be null and you get an exception, trying to convert null to string.

like image 30
IliaJ Avatar answered Jan 24 '26 06:01

IliaJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!