Visual C# 2008 Working Winforms Example
The following example demonstrates implementing a very simple class property. The class is named Cyborg which includes one property named CyborgName.
Create a form and place a button on it and add code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_Properties
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Cyborg MyRobot = new Cyborg();
MyRobot.CyborgName = "John";
MessageBox.Show("Hi, my name is " + MyRobot.CyborgName + ".");
}
}
public class Cyborg : System.Object
{
private string cyborgName;
public string CyborgName
{
get
{
return cyborgName;
}
set
{
cyborgName = value;
}
}
}
}
Referencing Properties within the Class and from an Object Instance
From within the class code (and descendant classes), you can use a property by using the property name (you cannot use class dot notation), or you can also refer directly to the member variable if it's within scope. In our example above, you can use either the property or member field within the class (CyborgName) or the member field (cyborgName). You can use the private member field within the class because that is the definition of private visibility. However, you can only use the property CyborgName in descendant classes. You cannot use ClassName.PropertyName.
For object instances, you use ObjectInstance.PropertyName as in MyRobot.CyborgName.
For example, you can add the following method to our Cyborg class above:
public virtual void IntroduceYourself()
{
if (CyborgName == null)
MessageBox.Show("Hi, I do not have a name yet.");
else
MessageBox.Show("Hi, my name is " + CyborgName + ".");
}
Then you can add two buttons to the form and consume this new method as follows:
private void button2_Click(object sender, EventArgs e)
{
Cyborg MyRobot = new Cyborg();
MyRobot.IntroduceYourself();
}
private void button3_Click(object sender, EventArgs e)
{
Cyborg MyRobot = new Cyborg();
MyRobot.CyborgName = "Cameron";
MyRobot.IntroduceYourself();
}