An interface is a class with only signatures of methods properties and events without any implementation.
It is up to implementing class to add functionality . Your can't create an instance of interface.
Interface is an contract between an interface and implementing class that the implementing class should implements all the members of the interface.
It is possible to have multiple interface inheritance.
Start a new Windows Forms application or Wpf Application.
Add a new Interface by selecting Project, Add New Item and Interface from the Add NewItem Dialog.
interface ISpecialization
{
string Specialization { get; set; }
}
Likewise create another Interface called IHobby.
interface IHobby
{
string Hobby { get; set; }
}
Now create a class which implements both ISpecailization and IHobby.
class Person : ISpecialization, IHobby
{
public string Hobby { get; set; }
public string Specialization { get; set; }
}
Now in Wpf Form you can instantiate Person class and use it.
Person Shalvin;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Shalvin = new Person();
Shalvin.Specialization = ".Net";
Shalvin.Hobby = "Blogging";
}
private void btnHobby_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Shalvin.Hobby);
}
private void btnSpecialization_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Shalvin.Specialization);
}
Though we are using inheritance operator (:) behind the scene it is doing an implementation as is evident form the IL code below.
If your are not conversant with Intermediate Language visi my blog : http://shalvinpd.blogspot.com/2008/02/intermediate-language.html
Sunday, June 8, 2008
C# Interface
Monday, March 24, 2008
Creating and Consuming Class Library in C#, Object Initializer
Knowledge of working with the class is essential in working with technologies like Web Service, Windows Communication Framework (MCF), Creating ASP .Net Web Controls, Model View Controller (MVC), etc.
I have already demonstrated creating class modules in C# WPF Creating Class with Constructors.
In that blog I creating the class by adding a class to the existing project. The drawback with that model is you can't use the class library outside the project.
Creating Class Library
In Visual Studio Select Class Library Project.
Visual Studio will create a project with a class called Class1. Better rename the class to Bank.
In this exercise we will be creating a Bank Class with one property called Balance and two methods Deposit and Withdraw.
public 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;
}
}
Consuming Class Library
Create a Windows Forms Application. You have add a reference to the dll by going to Project, Add Reference.
Select Browse tab in the dialog.
Navigate to the bin directory inside Release folder of the project and select the dll.
Now you can use the dll in your project just like you use the .Net class libraries.
Create a visual interface as shown below.
using ShalvinBankLib;
Bank ShalvinBank;
private void Form1_Load(object sender, EventArgs e)
{
ShalvinBank = new Bank();
}
private void ShowBalance()
{
lblCurBal.Text = ShalvinBank.Balance();
txtAmount.Text = "";
txtAmount.Focus();
}
private void btnDeposit_Click(object sender, EventArgs e)
{
ShalvinBank.Deposit(Int32.Parse(txtAmount.Text);
ShowBalance();
}
private void btnDeposit_Click(object sender, EventArgs e)
{
ShalvinBank.Withdraw(Int32.Parse(txtAmount.Text);
ShowBalance();
}
}
C# 3.0 Object Initializer
With C# 3.0 it is possible to initialize a class with
Bank ShalvinBank = new Bank { Balance = 5000 };
MessageBox.Show(ShalvinBank.Balance.ToString());
Thus the class can be initialized event without creating a constructor.
Additional Note on Class Libraries
It is very much possible to have forms inside class libraries. This is very useful in ERP type applications where new modules can be easily plugged into existing application simply be setting a reference to the class library and invoking the form from the parent application.
Form Visual Interface Code
private void InitializeComponent()
{
this.btnWithdraw = new System.Windows.Forms.Button();
this.btnDeposit = new System.Windows.Forms.Button();
this.txtAmount = new System.Windows.Forms.TextBox();
this.lblCurBal = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnWithdraw
//
this.btnWithdraw.Location = new System.Drawing.Point(128, 137);
this.btnWithdraw.Name = "btnWithdraw";
this.btnWithdraw.Size = new System.Drawing.Size(75, 23);
this.btnWithdraw.TabIndex = 11;
this.btnWithdraw.Text = "Withdraw";
this.btnWithdraw.UseVisualStyleBackColor = true;
//
// btnDeposit
//
this.btnDeposit.Location = new System.Drawing.Point(36, 137);
this.btnDeposit.Name = "btnDeposit";
this.btnDeposit.Size = new System.Drawing.Size(75, 23);
this.btnDeposit.TabIndex = 10;
this.btnDeposit.Text = "Deposit";
this.btnDeposit.UseVisualStyleBackColor = true;
//
// txtAmount
//
this.txtAmount.Location = new System.Drawing.Point(116, 81);
this.txtAmount.Name = "txtAmount";
this.txtAmount.Size = new System.Drawing.Size(100, 20);
this.txtAmount.TabIndex = 9;
//
// lblCurBal
//
this.lblCurBal.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblCurBal.Location = new System.Drawing.Point(116, 34);
this.lblCurBal.Name = "lblCurBal";
this.lblCurBal.Size = new System.Drawing.Size(87, 23);
this.lblCurBal.TabIndex = 8;
//
// Label2
//
this.Label2.AutoSize = true;
this.Label2.Location = new System.Drawing.Point(30, 44);
this.Label2.Name = "Label2";
this.Label2.Size = new System.Drawing.Size(46, 13);
this.Label2.TabIndex = 7;
this.Label2.Text = "Balance";
//
// Label1
//
this.Label1.AutoSize = true;
this.Label1.Location = new System.Drawing.Point(33, 88);
this.Label1.Name = "Label1";
this.Label1.Size = new System.Drawing.Size(43, 13);
this.Label1.TabIndex = 6;
this.Label1.Text = "Amount";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.btnWithdraw);
this.Controls.Add(this.btnDeposit);
this.Controls.Add(this.txtAmount);
this.Controls.Add(this.lblCurBal);
this.Controls.Add(this.Label2);
this.Controls.Add(this.Label1);
this.Name = "Form1";
this.Text = "Shalvin P D";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.Button btnWithdraw;
internal System.Windows.Forms.Button btnDeposit;
internal System.Windows.Forms.TextBox txtAmount;
internal System.Windows.Forms.Label lblCurBal;
internal System.Windows.Forms.Label Label2;
internal System.Windows.Forms.Label Label1;
Related Blogs
.Net Remoting Walkthrough
Saturday, January 12, 2008
WPF and Silverlight Creating Class with Constructors
(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
Monday, January 7, 2008
.Net Multi-Tier Application
This blog takes up the issue of creating multi tier application with VB.Net (Windows Forms) and C# (Asp .Net).
Start up with creating two stored procedures.
create procedure spAllCategories
as
select * from Categories
go
create procedure spInsertCategories (@pCategoryName varchar(40), @pDescription varchar(60))
as
insert into Categories values (@pCategoryName, @pDescription)
go
Create an new class Library project called ShalvinLib and add two methods that will call the stored procedures. This is going to act as the business tier.
Imports System.Data.SqlClient
Public Class BusinessLayer
Public Shared Function GetCategories() As DataTable
Dim cnn As New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind;Data Source=.\sqlexpress")
cnn.Open()
Dim ds As New DataSet
Dim da As New SqlDataAdapter("spAllCategories", cnn)
da.Fill(ds, "Cat")
Return ds.Tables("Cat")
End Function
Public Shared Sub InsertCategories(ByVal mCategoryName As String, ByVal mDescription As String)
Dim cnn As New SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind;Data Source=.\sqlexpress")
cnn.Open()
Dim cmd As SqlCommand
cmd = New SqlCommand("spInsertCategories " + mCategoryName + ", " + mDescription, cnn)
cmd.ExecuteNonQuery()
End Sub
End Class
C# and Asp.Net
Here instead of using Windows Forms I am opening a Asp.Net Application and Instead of starting a new class Library I am adding a Class to the existing project.
web.config
using System.Data.SqlClient;
public static DataTable GetCategories()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
SqlDataAdapter da = new SqlDataAdapter("spAllCategories", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "Cat");
return ds.Tables["Cat"];
}
public static void InsertCategories(string mCategoryName, string mDescription)
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
cnn.Open();
string strSql = "spInsertCategory '" + mCategoryName + "', '" + mDescription + "'";
SqlCommand cmd = new SqlCommand(strSql , cnn);
cmd.ExecuteNonQuery();
}
Having created the class library dll, we can proceed to create a windows forms application.
Set a reference to the class library. Create the visual interface and invoke the methods of class library.
Dim bl As New ShalvinLib.BusinessLayer
Private Sub frmShowCategories_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.DataSource = bl.GetCategories
End Sub
C# and Asp .Net
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = BusinessLayer.GetCategories();
DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
BusinessLayer.InsertCategories("Books", ".Net Books");
Response.Write("Record Saved");
}
Happy programming
