Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Adding Properties to an Object in C# is Different than Java and C++
By Kyle Lutes

Rate This Article: Add This Article To:

Using C#'s syntax for adding properties to a class, you can create cleaner code than was possible in Java or C++. The techniques for doing so, however, may go against your earlier training: you'll probably want to declare the class public.

One advantage of object-oriented programming (OOP) languages is the ability to model objects by coding both their data and behavior together in a single class. Previous to OOP, typically you would define a data structure (i.e. a struct, or user-defined type) in one place in your code, and functions to manipulate that data in another. An object has two kinds of data. I'll attempt to describe them here, but like most disciplines, OOP uses a lot of jargon words and frequently there are many words for the same concept.

One kind of data an object has is its private data. This private data, often described as the data that makes up an object's state, is implemented by declaring variables in the class file. These variables are referred to as data members, fields, member variables, and instance variables. I use the term data members and the naming convention of prefixing private variables with a lowercase m.

The other kind of data an object has is its public properties, sometimes referred to as attributes. Public properties, along with the public methods (and to a lesser extent, public events) are said to make up an object's interface. (That's important for code reuse reasons, because to reuse an object all you have to know is its interface and not its implementation.) I use the term Properties and by convention, I begin property names with an uppercase character.

In my experience, for each property your class exposes, you are likely to find a single member variable that holds that property's value. This member variable is then exposed as a property using one of several techniques mentioned below.

C# has a specific syntax for adding properties to a class, which allows much cleaner code when accessing a property when compared to Java or C++. Suppose you are creating a person class and need properties for FirstName, MiddleName, and LastName. In C#, you would use the properties like this:

clsStudent bob = new clsStudent();
   ...

bob.FirstName = "Bob";

bob.MiddleName = "B.";

bob.LastName = "Roberts";

... string bobsFirstName = bob.FirstName;

But in Java you typically would see the properties being used like this:

   Student bob = new Student();
   ...
   bob.setFirstName("Bob");
   bob.setMiddleName("B.");
   bob.setLastName("Roberts");
   ...
   String bobsFirstName = new String(bob.getFirstName());

You implement the properties in C# differently than in Java. The C# language has syntax for so-called get and set accessor methods. For example, in C# you could define the person class as:

public class clsStudent

{ private string mFirstName; private string mMiddleName; private string mLastName; public string FirstName { get { return mFirstName; } set { mFirstName = value; } } public string MiddleName { get { return mMiddleName; } set { mMiddleName = value; } } public string Last { get { return mLastName; } set { mLastName = value; } } }

The code inside the get block is executed whenever the property value is retrieved, and the code inside the set block is executed whenever the property value is set equal to some value.

Coding get and/or set accessor methods allow you to:

  • Make a read-only property by coding a get only
  • Make a write-only property by coding a set only
  • Execute code whenever a property is accessed. For example, to validate the contents of the value being set
  • Change the way the data is stored internally in the class without affecting other parts of the project
  • Make properties that are based on the values of other properties. For example:
public string FullName
{
   get
   {
      string fullName;
      fullName = mFirstName + " "
      + mMiddleName + " "
      + mLastName;
      return fullName;
   }
}

If the property doesn't meet any of the above criteria, it is probably okay to declare the variable as public, like this:

public class clsStudent
{
   public string FirstName;
   public string MiddleName;
   public string LastName;
}

You might be screaming, “Wait! That's terrible advice! You aren't supposed to declare class variables public!”

If you have experience with C++ or Java, no doubt you've heard (or read, or been taught, or preached to, or forced) that you should never make properties by declaring a member variable public. Instead, you should always declare it private and code methods for accessing an object's state. Should you follow this rule when coding in C#?

The first thing to ask is, “Why does everyone say to do it this way?” As in the old story of the young bride cutting the ends off the pot roast because that's how her mother taught her, always declaring member variables as private seems just as ignorant to me.

The reason Java and C++ programmers do this is because those languages have no special syntax for exposing class data. If you declare class variables as public you can never change the way the data is implemented without also changing the class's interface. And if you change the class's interface, you break the encapsulation rule and would have to search for and modify all code in all projects that use that class.

Let's compare what the languages let you do. In Java, say, you define a class like this:

public class Account extends Object
{
   public float interestRate;
}

Then use it from another class like this:

...
Account acct = new Account();
acct.interestRate = acct.interestRate + 1.25;
...

Then, after the Account class has been used in an application for a while, you decide that your Account class really shouldn't allow an interest rate to be negative. Because you've made interestRate public, there is no way to add data validation logic unless you also change the class's interface. You now have to do what you should have done from the beginning — make the variable private, and use a getter and setter function to access the variable:

public class Account extends Object
{

private int interestRate; public int getInterestRate() { return interestRate; } public void setInterestRate(int theInterestRate) { if (theInterestRate < 0) { // Throw an exception here. } interestRate = theInterestRate; } }

But now you also have to change all the code that uses the class's interest rate property to use the getter and setter functions instead:

   ...
   Account acct = new Account();
   acct.setInterestRate(acct.getInterestRate() + 1.25);
   ...

Which is bad, very bad. This change wouldn't have been necessary if you would have made the variable private and coded a getter and setter to begin with.

The reason you don't have to worry about this in C# (and VisualBasic and VB.NET for that matter) is because the language does have special syntax for exposing class data. The same Account class defined in C# would be coded in a class module named clsAccount and look like this:

public class clsAccount
{
    public float InterestRate; 
} 

And used from another class like this:

...
clsAccount acct = new clsAccount();
acct.InterestRate = acct.InterestRate + 1.25;
...

Now assume the same scenario. You decide that your Account class really shouldn't allow an interest rate to be negative. In C# you can change the variable to be private and add get and set methods without changing the class's interface:

public class clsAccount
{
    private float mInterestRate; 

    public float InterestRate
    {
	get
        {
            return mInterestRate;
        }
        set
        {
            if (value < 0)
            {
	        // Throw an exception here.
            {
            mInterestRate = value;
        }
    }
} 

The code that uses the interest rate stays the same because the interface of the class hasn't changed:

...
clsAccount acct = new clsAccount();
acct.InterestRate = acct.InterestRate + 1.25;
...

Nearly a quarter century of writing code has taught me that less code is generally better than more code, as long as all objectives are met. Less code is easier to type, easier to read, easier to maintain, and has fewer places for errors to occur. If I have a choice of adding a property to a class with one line of code by declaring a variable as public, rather than using 12 lines of code to declare a private variable and code get and set accessors for it, I'm choosing the one-line technique.




Discuss Adding Properties to an Object in C# is Different than Java and C++
 
>>> Be the FIRST to comment on this article!
 

 
 
>>> More ASP and .Net Coding Techniques Articles          >>> More By Kyle Lutes