Home and Learn: C# NET Course

Using Your Properties In C# .Net

<< Part of an ongoing lesson - first part is here >>

Now that you've set up a property in your class, you can put it to use. First, comment out any code for your first button. Place a new button on your form. Double click the button to get at the code.

The first thing to do is to create an object from your class:

A new Object created from a Class

In the above code, we've created a HappyBirthday object and called it birthdayMessage.

To pass something over to your new property, you use dot notation. So type birthdayMessage followed

The Property appears on the IntelliSense List

And there's the property you set up! The name of the property is MyProperty. That, however, is the default name. You can call your properties almost anything you like, just as you can with variables.

Double click your property to add it to your code.

To pass something in, you need an equals sign, followed by the information you want to pass to your property:

birthdayMessage.MyProperty = "Shahid";

In the code above, we're passing the text "Shahid" to our property.

To get something back out from your property, the syntax is this:

your_data = object_variable_name.property_name;

After the equals sign, you need the name of your object. Then type a dot. The IntelliSense list should appear again. Select your property from the list. End the line with the usual semicolon.

So add the following lines to your code:

Note the two lines that use the property:

birthdayMessage.MyProperty = "Shahid";
returnedMessage = birthdayMessage.MyProperty;

The first one is setting a value for the property. The second line is getting something back out. We're then handing it over to a string variable called returnedMessage. This can then be displayed in a message box.

If you're not sure quite what's going in, study the following images:

How C# Properties work

The image shows that the text "Shahid" from the button is getting handed over to the value variable in the set part of the property. The getMessage( ) method can then do something with this value. After it constructs the message, it hands it over to the birthdayMessage variable. The get part of the property can then see what's inside of the birthdayMessage variable.

Here's a pair of images showing what is happening when we get the value out of the property:

Getting the value of a Property

So the value in the class variable birthdayMessage is getting handed over to MyProperty in the button code. Once we get the value from the property, it is handed over to the returnedMessage variable.

In the next lesson, you'll learn about Class Constructors.

back to the c# net contents page


Buy the Book of this Course

Email us: enquiry at homeandlearn.co.uk