Reputation: 631
I have an objekt:
var object = new SomeObjectType()
{
Prop1 = null,
Prop2 = null,
Prop3 = 665
}
Assuming that Prop3
will be never null
, how can I verify if rest of the properties are null
, or one of them is not?
Right now I have:
if (object.Prop1 == null && object.Prop2 == null)
{
//do stuff
}
But this is very not elegant, especially if I have pore properties to verify. And I have no idea how could I use Null-conditional operators ?. and ?[] in my case.
How to do it with C#?
Upvotes: 0
Views: 274
Reputation: 5550
Putting it in a non-Linq way then try something like this as an outline:
int nullCount = 0
foreach (var property in object.GetType().GetProperties())
{
if (property.GetValue(object) == null) nullCount++;
}
if (nullCount == 1)
{
// do my first thing
}
else
{
// do my other thing
}
Upvotes: 1
Reputation: 799
You can achieve it with,
public bool hasMethod(object yourObject, string Prop)
{
return yourObject.GetType().GetMethod(Prop) != null;
}
Upvotes: 0
Reputation: 67487
There's many ways of doing this, perhaps one of the more easily readable is:
var o = new SomeObjectType // object is a keyword
{
Prop1 = null,
Prop2 = null,
Prop3 = 665
};
if(o is SomeObjectType { Prop1: null, Prop2: null } )
; // do stuff
Upvotes: 2