Share this question

Welcome to Teachnovice Q&A, where you can ask questions and receive answers from other members of the community.

This is a collaboratively edited question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How know if class member are not null or empty

0 like 0 dislike
1,024 views

I have a class with only string members like this :

[source language='c#']

public class MyClass 
{ 
    public string MyProp1 { get; set; } 
    public string MyProp2 { get; set; } 
}

[/source]

I create an instance :

[source language='c#']
Var myClass = new MyClass();
[/source]

Later in the code, I’d like to know if all the member (MyProp1 and MyProp2) are not null or empty. I know I can use a if of course but there is much more properties than 2 in my real code.

Is there a way to do this ?

asked Jan 5, 2012 by anonymous  
edited Jul 2, 2012

2 Answers

0 like 0 dislike

 

Using a dictionary based store for your properties is probably the easiest way of doing this:

public class MyClass
{
    private IDictionary<String, String> _store;

    public MyClass()
    {
        _store = new Dictionary<String, String>();
    }

    public string MyProp1 { 
        get { return GetOrDefault("MyProp1"); }
        set { _store["MyProp1"] = value; }
    }
    public string MyProp2 { 
        get { return GetOrDefault("MyProp2"); }
        set { _store["MyProp2"] = value; }
    }

    public Boolean HasData()
    {
        return _store.Any(x => !String.IsNullOrWhitespace(x.Value));
    }

    public Boolean IsEmpty()
    {
        return _store.All(x => String.IsNullOrWhitespace(x.Value));
    }   

    private String GetOrDefault(String propertyName)
    {
        if _store.ContainsKey(propertyName)
        {
            return _store[propertyName];
        }

        return String.Empty;
    }
}

Another method for doing this would be to compare it with a default instance:

public class MyClass
{
    public string MyProp1 { get; set; }
    public string MyProp2 { get; set; }

    public static readonly MyClass Empty = new MyClass();

    public Boolean HasData()
    {
        return !Empty.Equals(this);
    }

    public Boolean IsEmpty()
    {
        return Empty.Equals(this);
    }
}
answered Jul 2, 2012 by anonymous  
0 like 0 dislike

 

You can try to use the reflect to check the properties. You should need confirm that all the properties are public, and the type is string. Here is the code.

    public static bool IsNullOrEmpty(MyClass prop)
    {
        bool result = true;

        PropertyInfo[] ps = prop.GetType().GetProperties();

        foreach (PropertyInfo pi in ps)
        {
            string value = pi.GetValue(prop, null).ToString();

            if (string.IsNullOrEmpty(value))
            {
                result = false;
                break;
            }
        }

        return result;
    }
answered Jul 2, 2012 by anonymous  
...