.Net Developer World
Ankur Bhargav's Blog Ans Software Solution And Consult
Wednesday, November 20, 2013
Tuesday, October 1, 2013
How to Create Job & Task In SQL Server
you should create a job in SQL below is a sample T-SQL for create a job via SQL agent
USE msdb ;
GO
EXEC dbo.sp_add_job
@job_name = N'Weekly Sales Data Backup' ;
GO
EXEC sp_add_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_name = N'Set database to read only',
@subsystem = N'TSQL',
@command = N'ALTER DATABASE SALES SET READ_ONLY',
@retry_attempts = 5,
@retry_interval = 5 ;
GO
EXEC dbo.sp_add_schedule
@schedule_name = N'RunOnce',
@freq_type = 1,
@active_start_time = 233000 ;
USE msdb ;
GO
EXEC sp_attach_schedule
@job_name = N'Weekly Sales Data Backup',
@schedule_name = N'RunOnce';
GO
EXEC dbo.sp_add_jobserver
@job_name = N'Weekly Sales Data Backup';
GO
Get This Sp From MSDB Database From SQL System Database....
USE msdb ;
GO
EXEC dbo.sp_add_job
@job_name = N'Weekly Sales Data Backup' ;
GO
EXEC sp_add_jobstep
@job_name = N'Weekly Sales Data Backup',
@step_name = N'Set database to read only',
@subsystem = N'TSQL',
@command = N'ALTER DATABASE SALES SET READ_ONLY',
@retry_attempts = 5,
@retry_interval = 5 ;
GO
EXEC dbo.sp_add_schedule
@schedule_name = N'RunOnce',
@freq_type = 1,
@active_start_time = 233000 ;
USE msdb ;
GO
EXEC sp_attach_schedule
@job_name = N'Weekly Sales Data Backup',
@schedule_name = N'RunOnce';
GO
EXEC dbo.sp_add_jobserver
@job_name = N'Weekly Sales Data Backup';
GO
Get This Sp From MSDB Database From SQL System Database....
Tuesday, September 17, 2013
Manage Exceptions C#
private bool IsValid()
{
try
{
if (string.IsNullOrEmpty(TxtBroker.Text))
throw new Exception("Please Enter Valid Broker Name.");
if (string.IsNullOrEmpty(TxtPhone.Text))
throw new Exception("Please ENter Valid Phone No.");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void BtnSave_Click(object sender, EventArgs e)
{
try
{
if (IsValid())
{
//write your code
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Friday, July 26, 2013
Solve CLR error - .NET Frameworks
The reason of the problem is that the .NET Framework 4.0 has different requirement for app.config.
Solution: Change App.config
.NET 4.0 require config Sections in the App.config. If this section is missing in a app.config file, the program will crash at start. Details see http://msdn.microsoft.com/en-us/library/ms228245.aspx The following code example shows how to define a custom configuration section and define settings for that section.I also found there is error when I compile the setup project.
Because the VS2010 has no support for .NET Framework 2.0. It gives warning or error in compilation for .NET Framework 2.0 component. If a project needs it for setup as "Launch condition", these things need to be changed. Step 1. Change .vdproj file 1)Unload the installer or solution 2) open the .vdproj file in notepad and find the section "LaunceCondition" and update to:
"FrameworkVersion" = "8:.NETFramework,Version=v4.0"
or "FrameworkVersion" = "8:.NETFramework,Version=v4.0,Profile=Client"
"LaunchCondition"
{
{
"Name" = "8:.NET Framework"
"Message" = "8:[VSDNETMSG]"
"FrameworkVersion" = "8:.NETFramework,Version=v4.0"
"AllowLaterVersions" = "11:FALSE"
"InstallUrl" = "8:http://go.microsoft.com/fwlink/?LinkId=131000"
}
}
Step 2.
Copy the bootstrapper package to VS2010
If you take the .NET 2.0 package from the VS2008 bootstrapper packages folder and copy it to the corresponding location for VS2010, it works fine. I tested it in a virtual machine running Windows XP and no .NET. On Vista or Windows 7, the VS2008 packages are here: c:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFX (this is .NET 2.0)On Vista or Windows 7, the VS2010 packages are here: c:\Program Files\Microsoft SDKs\Windows\v7.0A\BootStrapper\Packages
Then the setup won't give error any more.
Monday, June 24, 2013
Adding attributes to an XML node in c#
XmlDocument doc = new XmlDocument();
//Create Root Element
XmlElement root = doc.CreateElement("Datasource");
//Create Var Tag Node
XmlElement var = doc.CreateElement("var");
//Apply Host Name Attribute to the var element
var.SetAttribute("name", "Host");
// create innertext element for var
XmlElement str = doc.CreateElement("string");
str.InnerText = "127.0.0.1";
//add inntertext element to the var node
var.AppendChild(str);
//add var node in root node
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Database");
str = doc.CreateElement("string");
str.InnerText = "TestDB";
var.AppendChild(str);
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Username");
str = doc.CreateElement("string");
str.InnerText = "Root";
var.AppendChild(str);
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Password");
str = doc.CreateElement("string");
str.InnerText = "Root123";
var.AppendChild(str);
root.AppendChild(var);
doc.AppendChild(root);
//Create Xml File To Application Start up Path Folder
doc.Save(Application.StartupPath + "_datasource.xml");
//Create Root Element
XmlElement root = doc.CreateElement("Datasource");
//Create Var Tag Node
XmlElement var = doc.CreateElement("var");
//Apply Host Name Attribute to the var element
var.SetAttribute("name", "Host");
// create innertext element for var
XmlElement str = doc.CreateElement("string");
str.InnerText = "127.0.0.1";
//add inntertext element to the var node
var.AppendChild(str);
//add var node in root node
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Database");
str = doc.CreateElement("string");
str.InnerText = "TestDB";
var.AppendChild(str);
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Username");
str = doc.CreateElement("string");
str.InnerText = "Root";
var.AppendChild(str);
root.AppendChild(var);
var = doc.CreateElement("var");
var.SetAttribute("name", "Password");
str = doc.CreateElement("string");
str.InnerText = "Root123";
var.AppendChild(str);
root.AppendChild(var);
doc.AppendChild(root);
//Create Xml File To Application Start up Path Folder
doc.Save(Application.StartupPath + "_datasource.xml");
how to get files and folder name in zip file c# ICSharpCode.SharpZipLib.Zip
ZipInputStream zip = new ZipInputStream( File.OpenRead(path));
ZipEntry item;
while ((item = zip.GetNextEntry()) != null )
{
Console.WriteLine(item.Name);
}
Saturday, June 22, 2013
What is MySQLDUMP And How To Use In C#
What is MySQLDUMP?
The mysqldump is console based executable utility and it allows us to assign a host of options to get the backup of a database to a file, a different MySQL server running anywhere in the world .
In fact MySQL does not backup our data instead of that it executes a set of basic sql syntaxes like "create table" and "insert into" in the MySQL server to re-create the database/s.
The mysqldump utility is present in the root directory of mysql, let us assume it is c:\mysql and you could find a folder bin in that directory. Using the mysqldump utility we can provide several commands so that we can change the way of taking backups.
1.Using This Command First You Will Download XAMPP
2.And Install It
3.After Installing Open Command Prompt
4.Go to [C:\xampp\mysql\bin] Folder Using cd Command
Like CD C:\xampp\mysql\bin
5.Now Type Command
mysqldump -hHostname -uUsername DatabaseName > FileName
Example
mysqldump -h127.0.0.1 -uroot TestDB > TestDB.sql
With Password
mysqldump -h127.0.0.1 -uroot -p123 TestDB > TestDB.sql
Now In C#
if (File.Exists(Application.StartupPath + "\\mysqldump.exe"))
{
try
{
using (StreamWriter sw = new StreamWriter (Application.StartupPath + "\\dump.bat"))
{
sw.Write("mysqldump -h127.0.0.1 -uroot -p123 TestDB > TestDB.sql");
sw.Close();
}
Shell(Application.StartupPath + "\\dump.bat", AppWinStyle.Hide , false);
File.Delete(Application.StartupPath + "\\dump.bat");
}
catch (Exception ex)
{}
}
else
{
MessageBox.Show("MySqlDump.Exe Not Found.");
}
Tuesday, June 18, 2013
download HTML Source in C#
using System.Net;
private string DownloadPagesource(string Url)
private string DownloadPagesource(string Url)
{
WebClient wc = new WebClient();
return wc.DownloadString(Url);
}
//This Method Return You To Website Page Source Code
//This Method Return You To Website Page Source Code
Thursday, June 13, 2013
C# Code to count kbps and download files from url
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace Example
{
public partial class Form1 : Form
{
string FileURL = "www.google.com";//your Url
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DownloadString(FileURL);
}
private void DownloadString(string URLStr)
{
WebClient WC = new WebClient();
WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
WC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WC_DownloadStringCompleted);
WC.DownloadStringAsync(new Uri(URLStr));
}
string Result = "";
void WC_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Result = e.Result;
}
void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//Progress Bar
PBarCsv.Value = (int)((e.BytesReceived * 100) / e.TotalBytesToReceive);
//Label For You File Total Byte
LblTotByt.Text = "Total Bytes : " + e.TotalBytesToReceive.ToString();
//Label For Remaining Bytes
LblRemByt.Text = "Remain Bytes : " + (e.TotalBytesToReceive - e.BytesReceived).ToString();
//Label For Current KBPS Download Speed
lblSpeed.Text = "KBPS : " + ConvertBytes(e.BytesReceived).ToString() + " Speed";
}
private double ConvertBytes(long bytes)
{
return (bytes / 1024);
//return (bytes / 1024f) / 1024f;
}
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace Example
{
public partial class Form1 : Form
{
string FileURL = "www.google.com";//your Url
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DownloadString(FileURL);
}
private void DownloadString(string URLStr)
{
WebClient WC = new WebClient();
WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
WC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WC_DownloadStringCompleted);
WC.DownloadStringAsync(new Uri(URLStr));
}
string Result = "";
void WC_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Result = e.Result;
}
void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//Progress Bar
PBarCsv.Value = (int)((e.BytesReceived * 100) / e.TotalBytesToReceive);
//Label For You File Total Byte
LblTotByt.Text = "Total Bytes : " + e.TotalBytesToReceive.ToString();
//Label For Remaining Bytes
LblRemByt.Text = "Remain Bytes : " + (e.TotalBytesToReceive - e.BytesReceived).ToString();
//Label For Current KBPS Download Speed
lblSpeed.Text = "KBPS : " + ConvertBytes(e.BytesReceived).ToString() + " Speed";
}
private double ConvertBytes(long bytes)
{
return (bytes / 1024);
//return (bytes / 1024f) / 1024f;
}
Wednesday, June 12, 2013
Ready State Property For Gecko.GeckoWebBrowser in c#,Wait Until Gecko.GeckoWebBrowser Is Busy,Workin and Loading
//Replace webbrowser.Readystate To This Method
private void WaitBrowser(Gecko.GeckoWebBrowser wb)
{
while (wb.IsBusy)
{
Application.DoEvents();
}
}
//Webbrowser Control Have Property To Check Browser Control Is
//Loading Or Not In Same Way In Gecko.GeckoWebBrowser Try This
//Code I Also Try IT
private void WaitBrowser(Gecko.GeckoWebBrowser wb)
{
while (wb.IsBusy)
{
Application.DoEvents();
}
}
//Webbrowser Control Have Property To Check Browser Control Is
//Loading Or Not In Same Way In Gecko.GeckoWebBrowser Try This
//Code I Also Try IT
Tuesday, June 11, 2013
Set Webbrowser Input Box Value In C# application
//wb as webbrowser
//if element have not assign id attribute
foreach (HtmlElement item in wb.Document.GetElementsByTagName("input"))
foreach (HtmlElement item in wb.Document.GetElementsByTagName("input"))
{
if (item != null && item.Name == "password")
{
item.SetAttribute("Value", "admin123");
break;
}
}//if element have assign id attribute
Userid.SetAttribute("Value", "admin");
Monday, June 10, 2013
Delegate In C#
using System;
namespace ConsoleApplication1
{
class Program
{
public delegate void Del(string message);
static void Main(string[] args)
{
// Instantiate the delegate.
Del handler = DelegateMethod;
// Call the delegate.
for (int i = 0; i < 9; i++)
{
handler("Hello World " + i.ToString());
}
Console.ReadKey();
}
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
}
}
Result
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8
namespace ConsoleApplication1
{
class Program
{
public delegate void Del(string message);
static void Main(string[] args)
{
// Instantiate the delegate.
Del handler = DelegateMethod;
// Call the delegate.
for (int i = 0; i < 9; i++)
{
handler("Hello World " + i.ToString());
}
Console.ReadKey();
}
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
}
}
Result
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8
Properties In C#
using System;
class Student
{
// Declare a Code property of type string
private string iCode = "Nothing";
public string Code
{
get
{
return iCode;
}
set
{
iCode = value;
}
}
// Declare a Name property of type string
private string iName = "Alfread";
public string Name
{
get
{
return iName;
}
set
{
iName= value;
}
}
// Declare a Age property of type int:
private int iAge= 15;
public int Age
{
get
{
return iAge;
}
set
{
iAge = value;
}
}
public override string ToString()
{
return "Code = " + iCode+", Name = " + iName + ", Age = " + iAge ;
}
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
class Student
{
// Declare a Code property of type string
private string iCode = "Nothing";
public string Code
{
get
{
return iCode;
}
set
{
iCode = value;
}
}
// Declare a Name property of type string
private string iName = "Alfread";
public string Name
{
get
{
return iName;
}
set
{
iName= value;
}
}
// Declare a Age property of type int:
private int iAge= 15;
public int Age
{
get
{
return iAge;
}
set
{
iAge = value;
}
}
public override string ToString()
{
return "Code = " + iCode+", Name = " + iName + ", Age = " + iAge ;
}
public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
C# Read And Write Byte In File With File Stream
using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}
C# Creating User Defined Exceptions
using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
C# Exception Handling
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Example
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Example
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
C# Namespaces
using System;
namespace first_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
namespace first_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
C# Interfaces
using System.Collections.Generic;
using System.Linq;using System.Text;
namespace InterfaceApplication{
public interface ITransactions{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{ private string tCode; private string date;
private double amount;
t1.showTransaction();
Console.ReadKey();
using System.Linq;using System.Text;
namespace InterfaceApplication{
public interface ITransactions{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{ private string tCode; private string date;
private double amount;
public Transaction()
{
tCode = " ";
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a) {
tCode = c;
amount = 0.0;
}
public Transaction(string c, string d, double a) {
tCode = c;
date = d;
amount = a;
} public double getAmount() {
return amount;
return amount;
} public void showTransaction() {
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester
{
static void Main(string[] args)
{
static void Main(string[] args)
{ Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}
Result:Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
}
Result:Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
C# Inheritance
Base and Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.
The syntax used in C# for creating derived classes is as follows:
class
{
...
}
class :
{
...
}
Example
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
Result
Total area: 35
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.
The syntax used in C# for creating derived classes is as follows:
{
...
}
class
{
...
}
Example
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
Result
Total area: 35
Subscribe to:
Posts (Atom)