using System;
using System.Collections;
using System.IO;
using System.Text;
namespace ArrayFileAndExceptionHandlingExample
{
/// <summary>
/// Summary description for Class1.
/// </summary>
///
public class Person //Create a person class with basic properties and methods
{
public int iAge; //Property
private string strName;
public string GetName()//Method
{
return strName;
}
public void SetName(string Name)
{
strName=Name;
}
public virtual void Play() //Virtual function
{
System.Console.WriteLine("I plays Nothing");
}
};
class ArrayFileAndExceptionHandling
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//Create a person Array
Person[] PersonArray= new Person[3] ; //Create an array of 3 persons
PersonArray[0]= new Person(); //Create theperson 1
PersonArray[0].SetName("Jerry"); //set the name
PersonArray[1]= new Person();
PersonArray[1].SetName("Thomas");
PersonArray[2]= new Person();
PersonArray[2].SetName("Jiss");
System.Console.WriteLine("Using Arrays" );
//Iterate through each element in the array using the foreach loop
foreach ( Person i in PersonArray )
{
System.Console.WriteLine(i.GetName() );
}
//Using ArrayList collection class
ArrayList PersonsList= new ArrayList(); //In namespace System.Collections
Person Person1= new Person();
Person1.SetName("Sachin");
PersonsList.Add(Person1);
Person Person2= new Person();
Person2.SetName("Rahul");
PersonsList.Add(Person2);
System.Console.WriteLine("Using Arraylist" );
foreach ( Person List in PersonsList )
{
System.Console.WriteLine(List.GetName() );
}
//Save these details to a file PersonDetails.txt
try //Exception handler
{
System.Console.WriteLine("Saving the details to the file" );
using (FileStream fs = File.Create("PersonDetails.txt")) //Creating the file with the specified name
{
// Add some information to the file.
foreach ( Person List in PersonsList )
{
byte[] bValues =new UTF8Encoding(true).GetBytes(List.GetName()); //Extracting the bytes
fs.Write(bValues, 0, bValues.Length);//Writing the contents to the file
}
}
}
catch(Exception ex) //catch block
{
System.Console.WriteLine("Some Error Occour while saving :" +ex.Message );
}
}
}
}