iterate Through Class Fields
I have some classes with a lot of fields I need to check. Its takes so much duplicated code to check each field so I want to iterate through each field.
How can I do it? It doesn't compile.
Code:
public class Person
{
// all fields are required
private string firstName;
private string middleName;
private string lastName;
public bool IsValid()
{
foreach(string str in this)
{
if (str == string.Empty)
{
return false;
}
}
return true;
}
It should check first middle and last name fields and return false if any are empty. But it doesn't compile.
What is the correct syntax?
Thanks.
Re: iterate Through Class Fields
Check out some of the classes in the System.Reflection namespace. Your more than likely going to need to use them.
Re: iterate Through Class Fields
Code:
public class Person
{
// all fields are required
private string firstName;
private string middleName;
private string lastName;
private IEnumerable<string> Fields
{
get
{
yield return this.firstName;
yield return this.middleName;
yield return this.lastName;
}
}
public bool IsValid()
{
foreach (string str in this.Fields)
{
if (String.IsNullOrEmpty(str))
{
return false;
}
}
return true;
}
}
Re: iterate Through Class Fields
Thank You!
I am going to try that and see if it works. That is pretty cool. I might run into one problem because in some of my classes I have more then one type, for example:
Code:
public class Person
{
private string firstName;
private string lastName;
private string middleName;
private DateTime HireDate;
private int Age;
}
I'm not sure how this will handle when the types are not all string but I will try to modify it.
I've never seen the yield keyword before. I looked in my C# Reference book and it explained what it did, but I didn't really understand the explenation.
I'm guessing that it just stops execution, and gives the calling function time to act on the current field, one the calling function is done the get property returns the next item.