(I have updated this blog on Mar 23, 2010 to showcase Silverlight 4 and Visual Studio 2010.
The same will work with WPF)
Create a new Silverlight 4 Application in Visual Studio 2010.
Creating a Silverlight Application Project creates two projects one a Silverlight Project and another a Web Project used for Hosting Silverlight.
Select Silverlight Project, Add a class by selecting Project, Add class menu option. Give the class a good name say Bank.
So we are going to create a Bank Class with two properties and one method.
In this article we are going to take up the issue of creating a class in C#.
C# has the notion of read write, read only and write only properties. Here we are going to have one read write properties, Bank.
For creating a class there property procedures. For read write property we should have both getter and setter and a private memory variable which actually holds the value. Getter is used for returning the value of the private memory variable and Setter is used for setting a value to the private memory variable which in effect reflects the value of the property.
The methods are Deposit and Withdraw.
I am also implementing a default and a parameterized constructor.
Here is the code of Bank class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpFCSClass
{
class Bank
{
public Bank()
{
miBalance = 5000;
}
public Bank(int mAmount)
{
Balance = mAmount;
}
private int miBalance;
public int Balance
{
get {
return miBalance;
}
set {
miBalance = value;
}
}
public void Deposit(int Amount)
{
Balance = Balance + Amount;
}
public void Withdraw(int Amount)
{
Balance = Balance - Amount;
}
}
}
Having created the class we can shift out attention to the presentation layer. The presentation layer can be anything ranging from Windows Forms Application, Web Forms Application, WPF etc. I decided to choose WPF.
Bank ShalvinBank = new Bank(2000);
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ShowBal();
}
private void ShowBal()
{
lblCurBal.Content = ShalvinBank.Balance.ToString();
txtAmount.Text = "";
txtAmount.Focus();
}
private void btnDeposit_Click(object sender, RoutedEventArgs e)
{
ShalvinBank.Deposit(Int32.Parse(txtAmount.Text));
ShowBal();
}
private void btnWithdraw_Click(object sender, RoutedEventArgs e)
{
ShalvinBank.Withdraw(Int32.Parse(txtAmount.Text));
ShowBal();
}
Happy Programming
shalvin@gmail.com
Showing posts with label Class Properties. Show all posts
Showing posts with label Class Properties. Show all posts
Saturday, January 12, 2008
WPF and Silverlight Creating Class with Constructors
Subscribe to:
Posts (Atom)