What is best way to check if any of the property of object is null or empty?

2.2k views Asked by At

I am creating Json file, and before creating i want to check if any of the property is empty of not.. And I want to create abstract method for that. So i dont have to write again and again.

public JObject CreatUserJson(Account lacc)
        {
            JObject pin = new JObject(
                new JProperty("email", lacc.email),
                new JProperty("fullname", lacc.fullname),
                new JProperty("phonenumber", lacc.phonenumber),
                new JProperty("ip_address", lacc.ip_address),
                new JProperty("password", lacc.password),
                new JProperty("client_id", Settings.Globals.CLIENT_ID),
                new JProperty("client_secret", Settings.Globals.CLIENT_SECRET)

        );
            return pin;
        }

This is how i defined my method and there are similar methods like this, I want standard way to check and throw exception if any value is missing..

public JObject IncomingWireNoticeJson(SyanpasePayLib.Resources.Wire lWire)
        {
            JObject pin = new JObject(
                new JProperty("amount", lWire.amount),
                new JProperty("status_url", lWire.status_url),
                new JProperty("memo", lWire.memo),
                new JProperty("oauth_consumer_key", lWire.oauth_consumer_key)
                );
            return pin;
        }

This is other example of method,there is no similarity. I just want to loop through and throw exception if any of the values are missing.

For instance, I know for CreatUserJson I require minimun 4 inputs and max 8 inputs..

Same way for IncomingWireNoticeJson I require minimun 2 inputs and max 4 inputs..

If range is greater then or less then the min and max, then it should throw error.. (This part i can manage, but i dont know how to define standard way to loop through this object)
Can some one help me with this.. ?

1

There are 1 answers

0
Dacker On

I think JObject has a method called Properties(). So you can loop through the results of that and check whether the values are not null.

foreach (JProperty property in pin.Properties()) 
{
    if (string.IsNullOrWhiteSpace(property.Value)) 
    {
        throw new Exception("Some exception");
        //Or perform count for minimum/maximum check 
    }
}

The minimum and maximum check is also easy todo if you use the Properties() method. Example can be easily rewritten using Linq too, but for explanation and expanding logic purposes I have written the normal version.