Reputation: 13
There are few properties that need to be in sync and required null check before it's use. They are on different class. What will be the better way to keep them in sync? Example:
public class A
{
public string Name { get; set; }
public string VNumber { get; set; }
public string VLNumber { get; set; }
}
//Method One has below check:
if (new[] { A.Name, A.VNumber, A.VLNumber }
.Any(string.IsNullOrEmpty))
{
//Some error message;
}
//Somewhere else:
public class B
{
public string Name { get; set; }
public string VNumber { get; set; }
public string VLNumber { get; set; }
}
//Method Two has below check:
if (string.IsNullOrEmpty(B.Name))
{
return false;
}
if (string.IsNullOrEmpty(B.VNumber))
{
return false;
}
if (string.IsNullOrEmpty(B.VLNumber))
{
return false;
}
Upvotes: 0
Views: 2298
Reputation: 772
If you want a universal solution to check any class's public and string properties then you need to use reflections in c# (see Reflections in c#).
For this case you may use this method to check any class's string and public properties to null or empty:
public bool CheckAnyStringPublicPropertyIsNotEmpty(object obj)
{
var t = obj.GetType();
var properties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(w => w.CanRead && w.CanWrite)
.Where(w => w.PropertyType == typeof(string))
.Where(w => w.GetGetMethod(true).IsPublic)
.Where(w => w.GetSetMethod(true).IsPublic);
foreach (var prop in properties)
{
var propValue =(t.GetProperty(prop.Name).GetValue(obj,null)??string.Empty).ToString();
if (string.IsNullOrEmpty(propValue))
return false;
}
return true;
}
and you may use something like this in your case:
var aObj = new A();
var result1 = CheckAnyStringPublicPropertyIsNotEmpty(aObj); //false
var bObj = new B(){Name="BName",VLNumber="2",VNumber="3"}
var result2 = CheckAnyStringPublicPropertyIsNotEmpty(bObj); //true
Upvotes: 0
Reputation: 2619
Since class A
and class B
has the same properties, they could be one (or at least inherit a common base class). The null check also seems to make use of the same logic, so it would be reasonable to put it in the base class too.
// Abstract base class (no instance of it can be made).
public abstract class BaseClass
{
public string Name { get; set; }
public string VNumber { get; set; }
public string VLNumber { get; set; }
// Logic for the common null checks.
// This logic will be used for all of BaseClass's sub classes.
public bool AnyPropertyIsNull()
{
return string.IsNullOrEmpty(Name)
|| string.IsNullOrEmpty(VNumber)
|| string.IsNullOrEmpty(VLNumber);
}
}
// Inherits base class
public class A : BaseClass
{ }
// Inherits base class
public class B : BaseClass
{ }
Example usage of the classes:
var b = new B();
bool bHasNullValues = b.AnyPropertyIsNull();
Upvotes: 1