1

i need a method to check the all class properties for null value and if just one of the properties is null then return false. something like this:

public static bool Check<T>(T instance)
{
    foreach (var parameter in instance)
    {
        if (parameter == null)
            return false;
    }

    return true;
}

how can i do it?

Update: its not a duplicate question!!!. i already saw this link and the different is my class properties has different types (string, int, double ....). so i need a method to check them out to. here is one of my classes(some of them just have fields.)

public class WS_IN_SimpayTransaction
{
    [DataMember]
    public WS_IN_WebServiceIdentity wsIdentity;
    [DataMember]
    public WS_IN_SimpayTransactionParams simpayTransactionParams;
}
public class WS_IN_WebServiceIdentity
{
    private string WS_userName;
    private string WS_passWord;

    public string WS_UserName
    {
        set { this.WS_userName = value; }
        get { return this.WS_userName; }
    }
    public string WS_PassWord
    {
        set { this.WS_passWord = value; }
        get { return this.WS_passWord; }
    }
}
public class WS_IN_SimpayTransactionParams
{
        string amount;
        string itemDes;
        string productID;
        string mobileNumber;
        string bankType;
        double bankTransactionID;
        int transID;
        DateTime date;
        public string Amount
        {
            set { amount = value; }
            get { return amount; }
        }
        public string ItemDes
        {
            set { itemDes = value; }
            get { return itemDes; }
        }
        public string ProductID
        {
            set { productID = value; }
            get { return productID; }
        }
        public string MobileNumber
        {
            set { mobileNumber = value; }
            get { return mobileNumber; }
        }
        public string BankType
        {
            set { bankType = value; }
            get { return bankType; }
        }
        public double BankTransactionID
        {
            set { bankTransactionID = value; }
            get { return bankTransactionID; }
        }
        public int TransID
        {
            set { transID = value; }
            get { return transID; }
        }
        public DateTime Date
        {
            set { date = value; }
            get { return date; }
        }
}

long story short. its a little complicated.

Community
  • 1
  • 1
Mohammad
  • 2,724
  • 6
  • 29
  • 55
  • 3
    When you say class *parameters*, do you mean *properties*? If so, have a look at reflection - particularly `Type.GetProperties`. – Jon Skeet Aug 01 '15 at 06:46
  • its not a duplicate question!!!. i already saw this [link](http://stackoverflow.com/questions/22683040/how-to-check-all-properties-of-an-object-whether-null-or-empty) and the different is my class properties has different types (string, int, double ....) – Mohammad Aug 01 '15 at 06:56
  • Well an `int` and a `double` can't be null anyway, so you may need to add a filter for that, but it certainly looks like a duplicate to me. – Jon Skeet Aug 01 '15 at 06:57
  • unfortunately even int and double can be null in my case. the classes are the web service input and i cant filter it. – Mohammad Aug 01 '15 at 07:00
  • No, `int` and `double` values can never be null. Try it: `int x = null;` Nope, that's not going to compile. They may be 0 (or 0.0) but not null. It's important that you understand that before you go any further. – Jon Skeet Aug 01 '15 at 07:01
  • its a web service input!!! how can some one cant just call it with null values. interesting!!!! – Mohammad Aug 01 '15 at 07:03
  • Regardless of what you're *doing* with the properties, if you have a property of type `int`, it simply can't be null. Ditto any value type, e.g. `DateTime`. If you're unsure of some of the core aspects of C# like value types and nullity, I would *strongly* advise that you read a good C# book before starting to play with web services and reflection. – Jon Skeet Aug 01 '15 at 07:16
  • So now you want to know whether or not a type is a value type in order to filter it... look at `PropertyInfo.PropertyType` and `Type.IsValueType`... – Jon Skeet Aug 01 '15 at 07:19

2 Answers2

4

You can find your answer here , it may hep you

which states :

 bool IsAnyNullOrEmpty(object myObject)
 {
     foreach(PropertyInfo pi in myObject.GetType().GetProperties())
     {
         string value = (string)pi.GetValue(myObject);
         if(String.IsNullOrEmpty(value))
         {
             return false;
         }
     }
     return true;
 }
Community
  • 1
  • 1
Tirthak Shah
  • 515
  • 2
  • 11
  • You should have added a comment with a link to that answer instead of copy/pasting the code from it. – MarcinJuraszek Aug 01 '15 at 06:49
  • 4
    @MarcinJuraszek I don't think it's bad to copy and paste the code. Since Link answers can become invalid if the linked page changes and it's frustrating for the user while searching the answer to move from one link to another. – Litisqe Kumar Aug 01 '15 at 07:01
  • Yup, I did the same earlier, only put link, and someone suggested(may be exp person at SO) me to put it answer as well as put code too, as answer can edited after we put here as link, and questioner may distracted. its good to put here link(so that one can identify that question is duplicate) as well as answer(so that one can find ans at earliest) – Tirthak Shah Aug 01 '15 at 07:07
  • And somehow now I am getting down vote, :( – Tirthak Shah Aug 01 '15 at 07:08
2

Something like this (checking for null, note, that non-string property can be empty):

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
  // Or false, or throw an exception
  if (Object.ReferenceEquals(null, instance))
    return true;

  //TODO: elaborate - do you need public as well as non public properties? Static ones?
  var properties = instance.GetType().GetProperties(
    BindingFlags.Instance | 
    BindingFlags.Static | 
    BindingFlags.Public | 
    BindingFlags.NonPublic);

  foreach (var prop in properties) {
    if (!prop.CanRead) // <- exotic write-only properties
      continue;
    else if (prop.PropertyType.IsValueType) // value type can't be null
      continue;

    Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

    if (Object.ReferenceEquals(null, value))
      return false;

    //TODO: if you don't need check STRING properties for being empty, comment out this fragment
    String str = value as String; 

    if (null != str)
      if (str.Equals(""))
        return false;
  }

  return true;
}

Edit: the updated example provided shows, that you want to check fields as well as properties, not properties alone; in that case:

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
  // Or false, or throw an exception
  if (Object.ReferenceEquals(null, instance))
    return true;

  //TODO: elaborate - do you need public as well as non public field/properties? Static ones? 
  BindingFlags binding =
    BindingFlags.Instance |
    BindingFlags.Static |
    BindingFlags.Public |
    BindingFlags.NonPublic;

  // Fields are easier to check, let them be first
  var fields = instance.GetType().GetFields(binding);

  foreach (var field in fields) {
    if (field.FieldType.IsValueType) // value type can't be null
      continue;

    Object value = field.GetValue(field.IsStatic ? null : instance);

    if (Object.ReferenceEquals(null, value))
      return false;

    //TODO: if you don't need check STRING fields for being empty, comment out this fragment
    String str = value as String;

    if (null != str)
      if (str.Equals(""))
        return false;

    // Extra condition: if field is of "WS_IN_" type, test deep:
    if (field.FieldType.Name.StartsWith("WS_IN_", StringComparison.OrdinalIgnoreCase))  
      if (!Check(value))
        return false; 
  }

  // No null fields are found, let's see the properties
  var properties = instance.GetType().GetProperties(binding);

  foreach (var prop in properties) {
    if (!prop.CanRead) // <- exotic write-only properties
      continue;
    else if (prop.PropertyType.IsValueType) // value type can't be null
      continue;

    Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

    if (Object.ReferenceEquals(null, value))
      return false;

    //TODO: if you don't need check STRING properties for being empty, comment out this fragment
    String str = value as String;

    if (null != str)
      if (str.Equals(""))
        return false;
  }

  return true;
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • thank you so much dear @Dimitry. but are sure it works? i tested with a one of my classes with null value but it returns true!. – Mohammad Aug 01 '15 at 07:09
  • @Dan: Could you provide an example of the test class? – Dmitry Bychenko Aug 01 '15 at 07:13
  • @Dan: look, you don't have *properties* at all: *fields* only. A property looks like that: `public String Amount {get; set;}`, while a field is something like this: `public String Amount;` – Dmitry Bychenko Aug 01 '15 at 07:23
  • thank you so much. honestly i didn't think its matter!!. one more question if some of my classes have fields and some other have properties? – Mohammad Aug 01 '15 at 07:32
  • @Dan: well, you can combine these two methods (rename them into, say, CheckProperties and CheckFields), e.g. check fields and then properties. – Dmitry Bychenko Aug 01 '15 at 07:35
  • sorry. i completely confused and start asking stupid questions. your method works just fine. but there is only one thing. if my class was like this: public class WS_IN_SimpayTransaction { [DataMember] public WS_IN_WebServiceIdentity wsIdentity; [DataMember] public WS_IN_SimpayTransactionParams simpayTransactionParams; }it dosnt work! whould you please tell me why? – Mohammad Aug 01 '15 at 07:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84868/discussion-between-dmitry-bychenko-and-dan). – Dmitry Bychenko Aug 01 '15 at 07:45