Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confusion about Set and Get... Need help

Status
Not open for further replies.

ehx6

IS-IT--Management
May 20, 2004
150
US
Hi, I am new to c# and reading a book about how to create classes. I was doing ok untill I read an article on

I have posted two code, one from the book, which I understand and the other from the article, which confused me. in the Book code, it first declared private variable_Name then made the public (set and get). it worked fine with me, but the article confused me in a way it first declared public variable then the Get and Set are public. Exactely opposit from what the book stated?
I was able to create an aspx page and call and set values and apply conditions if ().. for the Country public. But was not able to do the same in the public Name.
I am confused and do want to understand the point of the author's article... Is he trying to confuse his readers or what!!!
thanks for your help
Ehx
======================The Code ================
// what is in the book
private string _Country;
public string Country
{
get{return _Country;}
set{_Country= value;}
}

// what is in web article
public string Name;
private string _Name
{
get{return Name;}
set{Name= value;}
}
 
I think they made a mistake. Those lines should probably be reversed:
Code:
private string _Name;
public string Name
{
   get { return _Name; }
   set { _Name = value; }
}
The way they have it makes no sense.

BTW, you use properties because they allow you to go back later and add some validate. What if Name can only be 30 characters long? When using a public variable, there's no way to enforce that (or trim it off). But with a property, you now have a place to put that code:
Code:
private string _Name;
private const int _NameMaxLen = 30;

public string Name
{
   get { return _Name; }
   set { _Name = value.Substring(0, _NameMaxLen); }
}

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top