Javascript required
Skip to content Skip to sidebar Skip to footer

Using System Namespace Solution Class Solution

Answers to exercises in OOP with C# And .NET Library (Part 1)

1. Create a class to store details of student like rollno, name, course joined and fee paid so far. Assume courses are C# and ASP.NET with course fees being 2000 and 3000.

Provide the a constructor to take rollno, name and course.

Provide the following methods:

  • Payment(amount)
  • Print()
  • DueAmount property
  • TotalFee property
using System;  namespace st {     class Student     {         private int rollno;         private string name;         private string course;         private int feepaid;          public Student(int rollno, string name, string course)         {             this.rollno = rollno;             this.name = name;             this.course = course;         }          public void Payment(int amount)         {             feepaid += amount;         }          public void Print()         {             Console.WriteLine(rollno);             Console.WriteLine(name);             Console.WriteLine(course);             Console.WriteLine(feepaid);         }          public int DueAmount         {              get             {                 return TotalFee - feepaid;             }         }          public int TotalFee         {             get             {                 return course == "c#" ? 2000 : 3000;             }         }     }      class UseStudent     {          public static void Main()         {              Student s = new Student(1, "ABC", "c#");             s.Payment(1000);             s.Print();             Console.WriteLine(s.DueAmount);           }     } }      

Add a static member to store Service Tax, which is set to 12.3%. Also allow a property through which we can set and get service tax.

Modify TotalFee and DueAmount properties to consider service tax.

          using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace oop1 {     class Student2     {         private int rollno;         private string name;         private string course;         private int feepaid;          private static double servicetax = 12.3;          public Student2(int rollno, string name, string course)         {             this.rollno = rollno;             this.name = name;             this.course = course;         }          public void Payment(int amount)         {             feepaid += amount;         }          public void Print()         {             Console.WriteLine(rollno);             Console.WriteLine(name);             Console.WriteLine(course);             Console.WriteLine(feepaid);         }          public int DueAmount         {              get             {                 return TotalFee - feepaid;             }         }          public int TotalFee         {             get             {                 double total = course == "c#" ? 2000 : 3000;                 // service tax                 total = total + total * servicetax / 100;                 return (int) total;             }         }          public static double  ServiceTax         {             get             {                 return servicetax;             }             set             {                 servicetax = value;             }         }     } // Student2      class UseStudent2     {          public static void Main()         {              Student2 s = new Student2(1, "ABC", "asp.net");             s.Payment(1000);             s.Print();             Console.WriteLine(s.DueAmount);           }     } }      

2.Create the classes required to store data regarding different types of Courses. All courses have name, duration and course fee. Some courses are part time where you have to store the timing for course. Some courses are onsite where you have to store the company name and the no. of candidates for the course. For onsite course we charge 10% more on the course fee. For part-time course, we offer 10% discount.

Provide constructors and the following methods.

  • Print()
  • GetTotalFee()
          using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace st {     abstract class Course     {         protected string name;         protected int duration;         protected int coursefee;          public Course(string name, int duration, int coursefee)         {             this.name = name;             this.duration = duration;             this.coursefee = coursefee;         }          public virtual void Print()         {             Console.WriteLine(name);             Console.WriteLine(duration);             Console.WriteLine(coursefee);         }          public abstract int  GetTotalFee();     }      class ParttimeCourse : Course     {         private string timings;          public ParttimeCourse(string name, int duration, int coursefee, string timings) : base(name,duration,coursefee)         {             this.timings = timings;         }          public override void Print()         {             base.Print();             Console.WriteLine(timings);         }          public override int GetTotalFee()         {             return (int)  (coursefee * 0.90); // 10% discount         }      }      class OnsiteCourse : Course     {         private string company;         private int nostud;          public OnsiteCourse(string name, int duration, int coursefee, string company, int nostud)             : base(name, duration, coursefee)         {             this.company = company;             this.nostud = nostud;         }          public override void Print()         {             base.Print();             Console.WriteLine(company);             Console.WriteLine(nostud);         }          public override int GetTotalFee()         {             return (int)(coursefee * 1.1);  // 10% more         }      }      class TestCourse     {          public static void Main()         {             Course c = new OnsiteCourse("ASP.NET", 30, 5000, "ABC Tech", 10);             c.Print();             Console.WriteLine(c.GetTotalFee());              c = new ParttimeCourse("C#", 30, 3000, "7-8pm");             c.Print();             Console.WriteLine(c.GetTotalFee());         }       } }      

3. Create an interface called Stack with methods Push(), Pop() and property Length. Create a class that implements this interface. Use an array to implement stack data structure.

Create user-defined exceptions and ensure Push() and Pop() methods throw those exceptions when required.
using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace oop1 {     interface IStack     {         void Push(int v);         int Pop();         int Length { get; }     }      class StackFullException : Exception     {         public StackFullException()             : base("Stack Full")         {         }     }      class StackEmptyException : Exception     {         public StackEmptyException()             : base("Stack Empty")         {         }     }      class Stack  : IStack     {         private int[] a = new int[10];         private int top = 0;          public void Push(int v)         {              if (top == 10)                 throw new StackFullException();              a[top] = v;             top++;         }          public int Pop()         {             if (top == 0)                 throw new StackEmptyException();              top--;             return a[top];         }          public int Length         {             get             {                 return top;             }         }     }      class UseStack     {         public static void Main()         {             Stack s = new Stack();             s.Push(20);              Console.WriteLine(s.Pop());             Console.WriteLine(s.Length);              Console.WriteLine(s.Pop());          }     } }      

4.Answer the following.

  1. Can a static method access instance variable? [True/False]

    False

  2. A partial method must be in a _______ class.

    Partial class

  3. You cannot overload two methods that return different return types when names and parameters are same. [True/False]

    True

  4. In order to make property read-only, we need to use read-only keyword.[True/False]

    False. We need to omit Set method.

  5. A class can have more than one indexer with the same type of parameter.[True/False]

    False

  6. A class marked as sealed can have an abstract method. [True/False]

    False

  7. When you create a method in the derived class with the same name as a method in base class, by default, it is said to [override/shadow] the method in the base class.

    Shadow

  8. If a function returns control from a try block for which we have finally block then finally block is not executed and control returns from the function to caller. [True/False]

    False. Finally block is executed then control returns to caller

5. Create a form that takes loan amount and period, which is either 1 year or 2 years or 3 years.

The interest rates are as follows:

1 year - 10%
2 years - 12%
3 years - 15%

Calculate the total amount to be paid (amount + interest) and find out EMI (Every month installment) and display it to user.

          using System; using System.Drawing; using System.Windows.Forms;  namespace st {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void btnCalculateEMI_Click(object sender, EventArgs e)         {             try             {                 double amount = Double.Parse(txtLoanAmount.Text);                 int period = cmbPeriod.SelectedIndex + 1;                  double emi = 0;                 switch (period)                 {                     case 1: emi = (amount + (amount * 10 / 100)) / 12; break;                     case 2: emi = (amount + (amount * 12 / 100)) / 24; break;                     case 3: emi = (amount + (amount * 15 / 100)) / 36; break;                     default :                         MessageBox.Show("Please select period for your instalment!", "Error");                         return;                 }                  MessageBox.Show( String.Format ("Monthly Installment  : {0}", emi), "EMI");             }             catch (Exception ex)             {                 MessageBox.Show("Invalid Input. Please enter a valid amount for loan amount!", "Error");             }         }     } // class } // namespace      

6. Accept a string from user through keyboard and display it vertically.

using System; namespace st {     class StringVertical {           public static void Main() {              Console.Write("Enter a string : ");              string st = Console.ReadLine();               for ( int i  = 0 ; i < st.Length; i ++)              {                  Console.WriteLine (  st[i]);              }          } // main     } // class } // namespace      

7. Accept 10 strings from user and display the highest of all strings.

          using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace st {     class LargestString     {          public static void Main()         {              string largest = "";             for (int i = 1; i <= 10; i++)             {                 Console.Write("Enter a string : ");                 string st = Console.ReadLine();                  if (st.CompareTo(largest) > 0)                     largest = st;             } // for              Console.WriteLine("Largest of all strings : {0}", largest);         } // main      } // class } // namespace      

8. Create a class to store day, month and year. Ensure objects of this class are comparable.

using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace st {     class Date : IComparable          {         private int day, month, year;          public Date(int day, int month, int year)         {             this.day = day;             this.month = month;             this.year = year;         }          public int CompareTo(Date other)         {              if ( this.year - other.year != 0 )                  return  this.year - other.year;               if (this.month - other.month != 0)                  return this.month - other.month;               return this.day - other.day;         }     }      class TestDate     {          public static void Main()         {             Date d1 = new Date(10, 2, 2011);             Date d2 = new Date(20, 1, 2011);              Console.WriteLine(d1.CompareTo(d2));         }     } // TestDate } // namespace              

9. Accept a folder from user and a string. Display all files in the folder that contain the given string in the filename. Use a textbox to take folder name and another textbox for string. Use a Listbox to display the list of selected files.

        private void btnSearch_Click(object sender, EventArgs e)     {             DirectoryInfo d = new DirectoryInfo(txtFolder.Text);             FileInfo[] files = d.GetFiles();             lstFiles.Items.Clear();              foreach (FileInfo f in files)             {                 if (f.Name.Contains(txtString.Text))                     lstFiles.Items.Add(f.Name);             }     }      

10. Display only non blank lines of the given file.

using System; using System.IO;  namespace st {     class NonBlankLines     {         public static void Main()         {             Console.Write("Enter a filename : ");             string filename = Console.ReadLine();              StreamReader sr = new StreamReader(filename);              string line = sr.ReadLine();             while (line != null)             {                  if (line.Length > 0)                     Console.WriteLine(line);                 line = sr.ReadLine();             }             sr.Close();         } // Main     }  // class } // namespace      

11. Display lines that contain the given string in the given file.

using System; using System.IO;  namespace st {     class SearchFile     {         public static void Main()         {             Console.Write("Enter a filename : ");             string filename = Console.ReadLine();              Console.Write("Enter search string  : ");             string searchstring = Console.ReadLine();               StreamReader sr = new StreamReader(filename);              string line = sr.ReadLine();             while (line != null)             {                  if (line.Contains(searchstring))                     Console.WriteLine(line);                  line = sr.ReadLine();             }             sr.Close();          } // Main     } // class } // namespace      

12. Take source file, target file, source string and target string. Replace all occurrences of source string with target string while writing content from source file to target file.

using System; using System.IO;  namespace st {     class SearchReplace     {         public static void Main()         {             Console.Write("Enter a source file : ");             string srcfilename = Console.ReadLine();              Console.Write("Enter a target file : ");             string trgfilename = Console.ReadLine();              Console.Write("Enter search string  : ");             string searchstring = Console.ReadLine();              Console.Write("Enter replace string  : ");             string replacestring = Console.ReadLine();              StreamReader sr = new StreamReader(srcfilename);             StreamWriter sw = new StreamWriter(trgfilename);              string line = sr.ReadLine();             while (line != null)             {                 string newline = line.Replace(searchstring, replacestring);                 sw.WriteLine(newline);                 line = sr.ReadLine();             }             sr.Close();             sw.Close();         } // Main     } // class } // Namespace      

Using System Namespace Solution Class Solution

Source: http://www.srikanthtechnologies.com/books/ms.net4.5/oop1.html