bakunet
bakunet

Reputation: 631

How to check with C#, in more elegant way, if only some of the object properties are null?

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

Answers (3)

Peter Smith
Peter Smith

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

Nathan Getachew
Nathan Getachew

Reputation: 799

You can achieve it with,

public bool hasMethod(object yourObject, string Prop)
{
    return yourObject.GetType().GetMethod(Prop) != null;
}

Upvotes: 0

Blindy
Blindy

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

Related Questions