-
April 27th, 2009, 08:11 PM
#1
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.
-
April 27th, 2009, 10:44 PM
#2
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.
R.I.P. 3.5" Floppy Drives
"I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein
-
April 28th, 2009, 02:38 AM
#3
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;
}
}
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post.
-
April 28th, 2009, 10:32 AM
#4
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|