简体   繁体   中英

How to check if certain properties of an object are not empty in C#

I have a class

class A {
    propA { get; set; }
    propB { get; set; }
    propC { get; set; }
    target { get; set; }
}

I work out the target of class A and populate the class with user input. Each different target will mean different properties of the class are required(not empty/null).

So if my target is banana, then propA and propB must not be empty. If apple, then propB and propC must not be empty. I need to do this at the start of the application as to not keep doing checks in a later stage, as some methods and DB calls will require data etc.

What's the best way to code this? or even design-wise. Is it good practice to store what properties are required for each target in an enum? And then use what lazyberezovsky provided below to go through and check??

The above example only has 3 properties, but what I'm actually required to do has heaps more.

I only just started looking at ways to validate my code.

In summary, there are two parts to this question. - How to check whether a property of a class is empty - Storing a lists of different combined required properties somewhere to use against how to check

EDIT: sorry! I've edited to hopefully make more sense out of this.

Let me try to guess what question was about :)

Here is type validator, which can check existence of parameter's public properties:

public class TypeValidator<T>
{
    public bool IsPropertyExists(string propertyName)
    {
        Type type = typeof(T);
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
        foreach (PropertyInfo property in type.GetProperties(flags))
            if (property.Name == propertyName)
                return true;

        return false;
    }
}

Usage with your class:

TypeValidator<a> validator = new TypeValidator<a>();
validator.IsPropertyExists("PropB")

Or you can use it as extension method public static bool IsPropertyExists<T>(this T t, string propertyName) with any object or generic parameter. But for me reflection is evil :) Try to resolve this issue by design.

I think what you are after is model validation. If so, perhaps a good place to put your validation logic is in a method of Class A, like this:

Class A
{
   Nullable<int> propA { get; set; }
   int? propB { get; set; }
   int? propC { get; set; }
   string target { 
      get { return _target; } 
      set { 
         var oldtarget = _target;
         _target = value; 
         if !IsValid() 
         {
             _target = oldtarget;
             throw new Exception("Setting target to " 
                        + value 
                        + " is not possible, ....");
         }
      } 
   }

   public bool IsValid()
   {
       switch (_target)
       {
           case "banana":
              return propA.HasValue() && propB.HasValue();

           case "apple":
              return propB.HasValue() && propC.HasValue();
       }

       return true;
   }
}

How to check is propA is empty? Depends on what propA is... is it an int? a bool? a string? etc... assuming it's a int than you can use the method above...

Can't think of a more "generic" validation than IsValid(), that is, I can't think of a more generic way to validate without knowing more...

I guess you mean validation when you say a property exists.

You haven't specified if its an Web or Win Form/Wpf application (or whatelse).

You could implement IDataErrorInfo on you Classes and validate if properties have been filled right.

There are tons of examples to find when Googling on IDataErrorInfo + Validate but here are some which helped me in the past:

http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/

How to validate child objects by implementing IDataErrorInfo on parent class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM