35
C#.NET Programs for 5 th Sem CSE 1. Hello world program: TestHello.cs namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } 2. Application developed for Arithmetical Operations like Add, Sub, Mul, Div and Mod (Maths operator using calculator) namespace MathsOperators { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void calculateClick(object sender, RoutedEventArgs e) { try { if ((bool)addition.IsChecked) { addValues();

pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

  • Upload
    vocong

  • View
    221

  • Download
    1

Embed Size (px)

Citation preview

Page 1: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE

1. Hello world program:TestHello.cs

namespace TestHello

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Hello World!");

}

}

}

2. Application developed for Arithmetical Operations like Add, Sub, Mul, Div and Mod (Maths operator using calculator)

namespace MathsOperators{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private void calculateClick(object sender, RoutedEventArgs e) { try { if ((bool)addition.IsChecked) { addValues(); } else if ((bool)subtraction.IsChecked) { subtractValues(); } else if ((bool)multiplication.IsChecked) { multiplyValues(); }

Page 2: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE else if ((bool)division.IsChecked) { divideValues(); } else if ((bool)remainder.IsChecked) { remainderValues(); } } catch (Exception caught) { expression.Text = ""; result.Text = caught.Message; } }

private void addValues() { int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome = 0; // TODO: Add rhs to lhs and store the result in outcome outcome = lhs + rhs; expression.Text = $"{lhsOperand.Text} + {rhsOperand.Text}"; result.Text = outcome.ToString(); }

private void subtractValues() { int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome = 0; // TODO: Subtract rhs from lhs and store the result in outcome outcome = lhs - rhs; expression.Text = $"{lhsOperand.Text} - {rhsOperand.Text}"; result.Text = outcome.ToString(); }

private void multiplyValues() { int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome = 0; // TODO: Multiply lhs by rhs and store the result in outcome outcome = lhs * rhs; expression.Text = $"{lhsOperand.Text} * {rhsOperand.Text}"; result.Text = outcome.ToString(); }

private void divideValues() { int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome = 0; // TODO: Divide lhs by rhs and store the result in outcome outcome = lhs / rhs;

Page 3: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE expression.Text = $"{lhsOperand.Text} / {rhsOperand.Text}"; result.Text = outcome.ToString(); }

private void remainderValues() { int lhs = int.Parse(lhsOperand.Text); int rhs = int.Parse(rhsOperand.Text); int outcome = 0; // TODO: Work out the remainder after dividing lhs by rhs and store the result in outcome outcome = lhs % rhs; expression.Text = $"{lhsOperand.Text} % {rhsOperand.Text}"; result.Text = outcome.ToString(); } }}

3. C# Program for Demonstration for Primitive Data Types

namespace PrimitiveDataTypes{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private void typeSelectionChanged(object sender, SelectionChangedEventArgs e) { ListBoxItem selectedType = (type.SelectedItem as ListBoxItem); switch (selectedType.Content.ToString()) { case "int": showIntValue(); break; case "long": showLongValue(); break; case "float": showFloatValue(); break; case "double": showDoubleValue(); break; case "decimal": showDecimalValue();

Page 4: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE break; case "string": showStringValue(); break; case "char": showCharValue(); break; case "bool": showBoolValue(); break; } }

private void showIntValue() { int intVar; intVar = 42; value.Text = intVar.ToString(); }

private void showLongValue() { long longVar; longVar = 42L; value.Text = longVar.ToString(); }

private void showFloatValue() { float floatVar; floatVar = 0.42F; value.Text = floatVar.ToString(); }

private void showDoubleValue() { double doubleVar; doubleVar = 0.42; value.Text = doubleVar.ToString(); }

private void showDecimalValue() { decimal decimalVar; decimalVar = 0.42M; value.Text = decimalVar.ToString(); }

private void showStringValue() { string stringVar; stringVar = "forty two";

Page 5: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE value.Text = stringVar; // ToString not needed }

private void showCharValue() { char charVar; charVar = 'x'; value.Text = charVar.ToString(); }

private void showBoolValue() { bool boolVar; boolVar = false; value.Text = boolVar.ToString(); } }}

4. C# Programs to Demonstrate How to create the Method and Use methods

namespace DailyRate{ class Program { static void Main(string[] args) { (new Program()).run(); }

void run() { double dailyRate = readDouble("Enter your daily rate: "); int noOfDays = readInt("Enter the number of days: "); writeFee(calculateFee(dailyRate, noOfDays)); }

private void writeFee(double v) => Console.WriteLine($"The consultant's fee is: {v * 1.1}");

private double calculateFee(double dailyRate, int noOfDays) => dailyRate * noOfDays;

private int readInt(string v) { Console.Write(v); string line = Console.ReadLine(); return int.Parse(line);

Page 6: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE }

private double readDouble(string v) { Console.Write(v); string line = Console.ReadLine(); return double.Parse(line); } }}

5. Selection using methods:( if Statements)

namespace Selection{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private void compareClick(object sender, RoutedEventArgs e) { int diff = dateCompare(firstDate.Date.LocalDateTime, secondDate.Date.LocalDateTime); info.Text = ""; show("firstDate == secondDate", diff == 0); show("firstDate != secondDate", diff != 0); show("firstDate < secondDate", diff < 0); show("firstDate <= secondDate", diff <= 0); show("firstDate > secondDate", diff > 0); show("firstDate >= secondDate", diff >= 0); }

private void show(string exp, bool result) { info.Text += exp; info.Text += " : " + result.ToString(); info.Text += "\n"; }

private int dateCompare(DateTime leftHandSide, DateTime rightHandSide) { int result = 0;

if (leftHandSide.Year < rightHandSide.Year) { result = -1; } else if (leftHandSide.Year > rightHandSide.Year) {

Page 7: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE result = 1; } else if (leftHandSide.Month < rightHandSide.Month) { result = -1; } else if (leftHandSide.Month > rightHandSide.Month) { result = 1; } else if (leftHandSide.Day < rightHandSide.Day) { result = -1; } else if (leftHandSide.Day > rightHandSide.Day) { result = 1; } else { result = 0; }

return result; } }}

6. Conversion of Decimal Number to Octal Number Step by Step Using Do-While Loop

namespace DoStatement{ public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private void showStepsClick(object sender, RoutedEventArgs e) { int amount = int.Parse(number.Text); steps.Text = ""; string current = "";

do { int nextDigit = amount % 8; amount /= 8; int digitCode = '0' + nextDigit;

Page 8: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE char digit = Convert.ToChar(digitCode); current = digit + current; steps.Text += current + "\n"; } while (amount != 0); } }}

7. C# Program to Demonstrate the Working of Switch Statement

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace SwitchStatement{ /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private void copyClick(object sender, RoutedEventArgs e) { target.Text = ""; string from = source.Text; for (int i = 0; i != from.Length; i++) { char current = from[i];

Page 9: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE copyOne(current); } }

private void copyOne(char current) { switch (current) { case '<': target.Text += "&lt;"; break; case '>': target.Text += "&gt;"; break; case '&': target.Text += "&amp;"; break; case '\"': target.Text += "&#34;"; break; case '\'': target.Text += "&#39;"; break; default: target.Text += current; break; }

8. C# Program to Demonstrate the Working of While Statement

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.Storage;using Windows.Storage.Pickers;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;

Page 10: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSEusing Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace WhileStatement{ /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }

private async void openFileClick(object sender, RoutedEventArgs e) { FileOpenPicker fp = new FileOpenPicker(); fp.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; fp.ViewMode = PickerViewMode.List; fp.FileTypeFilter.Add("*");

StorageFile file = await fp.PickSingleFileAsync(); if (file != null) { fileName.Text = file.Path;

var fileStream = await file.OpenAsync(FileAccessMode.Read); var inputStream = fileStream.GetInputStreamAt(0); TextReader reader = new StreamReader(inputStream.AsStreamForRead()); displayData(reader); } }

private void displayData(TextReader reader) { source.Text = ""; string line = reader.ReadLine(); while (line != null) { source.Text += line + '\n'; line = reader.ReadLine(); } reader.Dispose(); } }}

Page 11: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE

9. C# Program to Write Constructor and Creation of Object(Finding distance between two points by distance formula using Classes:)

namespace Classes{ class Point { private int x, y; private static int objectCount = 0;

public Point() { this.x = -1; this.y = -1; objectCount++; }

public Point(int x, int y) { this.x = x; this.y = y; objectCount++; }

public double DistanceTo(Point other) { int xDiff = this.x - other.x; int yDiff = this.y - other.y; double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff)); return distance; }

public static int ObjectCount() => objectCount; }}namespace Classes{ class Program { static void doWork() { Point origin = new Point(); Point bottomRight = new Point(1366, 768); double distance = origin.DistanceTo(bottomRight); Console.WriteLine($"Distance is: {distance}"); Console.WriteLine($"Number of Point objects: {Point.ObjectCount()}"); }

Page 12: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE static void Main(string[] args) { try { doWork(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }}

8.Use value Parameters and reference parameters with doWork method:

using System;

namespace Parameters{ class Pass { public static void Value(ref int param) { param = 42; }

public static void Reference(WrappedInt param) { param.Number = 42; } }}namespace Parameters{ class WrappedInt { public int Number; }}namespace Parameters{ class Program

Page 13: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE { static void doWork() { int i = 0; Console.WriteLine(i); Pass.Value(ref i); Console.WriteLine(i);

WrappedInt wi = new WrappedInt(); Console.WriteLine(wi.Number); Pass.Reference(wi); Console.WriteLine(wi.Number); }

static void Main(string[] args) { try { doWork(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }}

10. C# Program for Structure and Enumerations:

using System;

namespace StructsAndEnums{ struct Date { private int year; private Month month; private int day;

public Date(int ccyy, Month mm, int dd) { this.year = ccyy - 1900; this.month = mm; this.day = dd - 1; }

public override string ToString() {

Page 14: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE string data = $"{this.month} {this.day + 1} {this.year + 1900}"; return data; }

public void AdvanceMonth() { this.month++; if(this.month == Month.December + 1) { this.month = Month.January; this.year++; } } }}using System;

namespace StructsAndEnums{ enum Month { January, February, March, April, May, June, July, August, September, October, November, December }}#region Using directives

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

#endregion

namespace StructsAndEnums{ class Program { static void doWork() { //Month first = Month.December; //Console.WriteLine(first); //first++; //Console.WriteLine(first);

//Date defaultDate = new Date(); //Console.WriteLine(defaultDate);

Date weddingAnniversary = new Date(2015, Month.July, 4); Console.WriteLine(weddingAnniversary);

Page 15: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE

Date weddingAnniversaryCopy = weddingAnniversary; Console.WriteLine($"Value of copy is {weddingAnniversaryCopy}");

weddingAnniversary.AdvanceMonth(); Console.WriteLine($"New value of weddingAnniversary is {weddingAnniversary}"); Console.WriteLine($"Value of copy is still {weddingAnniversaryCopy}"); }

static void Main() { try { doWork(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }}

11. PlayingCards using multidimensional array( 2 D Arrays):

namespace Cards{ enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }}

namespace Cards{ enum Suit { Clubs, Diamonds, Hearts, Spades }}namespace Cards{

class PlayingCard{

private readonly Suit suit; private readonly Value value;

public PlayingCard(Suit s, Value v){

this.suit = s;this.value = v;

}

public override string ToString()

Page 16: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE{

string result = $"{this.value} of {this.suit}"; return result;

}

public Suit CardSuit() { return this.suit; }

public Value CardValue() { return this.value; }

}}using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Popups;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;namespace Cards{

class Pack{

public const int NumSuits = 4; public const int CardsPerSuit = 13; private PlayingCard[,] cardPack; private Random randomCardSelector = new Random();

public Pack() { this.cardPack = new PlayingCard[NumSuits, CardsPerSuit]; for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++) { for (Value value = Value.Two; value <= Value.Ace; value++) { this.cardPack[(int)suit, (int)value] = new PlayingCard(suit, value); } } }

Page 17: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE public PlayingCard DealCardFromPack() { Suit suit = (Suit)randomCardSelector.Next(NumSuits); while (this.IsSuitEmpty(suit)) { suit = (Suit)randomCardSelector.Next(NumSuits); }

Value value = (Value)randomCardSelector.Next(CardsPerSuit); while (this.IsCardAlreadyDealt(suit, value)) { value = (Value)randomCardSelector.Next(CardsPerSuit); }

PlayingCard card = this.cardPack[(int)suit, (int)value]; this.cardPack[(int)suit, (int)value] = null; return card; }

private bool IsSuitEmpty(Suit suit) { bool result = true; for (Value value = Value.Two; value <= Value.Ace; value++) { if (!IsCardAlreadyDealt(suit, value)) { result = false; break; } } return result; }

private bool IsCardAlreadyDealt(Suit suit, Value value) => (this.cardPack[(int)suit, (int)value] == null); }}

CHAPTER 11-PARAMARRAYS1.Program.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace ParamsArray{ class Program {

Page 18: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE static void doWork() { Console.WriteLine(Util.Sum(2, 4, 6, 8, 10)); }

static void Main() { try { doWork(); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } } }}

2.Util.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace ParamsArray{ class Util { public static int Sum(params int[] paramList) { Console.WriteLine("Using parameter list"); if (paramList == null) { throw new ArgumentException("Util.Sum: null parameter list"); }

if (paramList.Length == 0) { throw new ArgumentException("Util.Sum: empty parameter list"); }

int sumTotal = 0; foreach (int i in paramList) { sumTotal += i; } return sumTotal; }

Page 19: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE public static int Sum(int param1 = 0, int param2 = 0, int param3 = 0, int param4 = 0) { Console.WriteLine("Using optional parameters"); int sumTotal = param1 + param2 + param3 + param4; return sumTotal; } }}

CHAPTER 12 Extension Method 1.Program.csusing System;using Extensions;

namespace ExtensionMethod{ class Program { static void doWork() { int x = 591; for(int i=2;i<=10;i++) { Console.WriteLine($"{x} in base {i} is {x.ConvertToBase(i)}"); } }

static void Main() { try { doWork(); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } } }}

2.Util.csusing System;

namespace Extensions{ static class Util { public static int ConvertToBase(this int i, int baseToConvertTo) {

Page 20: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE if (baseToConvertTo<2||baseToConvertTo>10) { throw new ArgumentException("Value cannot be converted to base " + baseToConvertTo.ToString()); }

int result = 0; int iterations = 0; do { int nextDigit = i % baseToConvertTo; i /= baseToConvertTo; result += nextDigit * (int)Math.Pow(10, iterations); iterations++; } while (i != 0); return result; } }}

CHAPTER 13: (simple class hierarchy for modeling different types of vehicles.) Create a hierarchy of classes

3.VECHICLES a)Airplane.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace Vehicles{ class Airplane : Vehicle { public void TakeOff() { Console.WriteLine("Taking off"); }

public void Land() { Console.WriteLine("Landing"); }

public override void Drive() { Console.WriteLine("Flying");

Page 21: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE } }}b)Car.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace Vehicles{ class Car:Vehicle { public void Accelerate() { Console.WriteLine("Accelerating"); }

public void Brake() { Console.WriteLine("Braking"); }

public override void Drive() { Console.WriteLine("Motoring"); } }}

c)Program.csusing System;

namespace Vehicles{ class Program { static void doWork() { Console.WriteLine("Journey by airplane:"); Airplane myPlane = new Airplane(); myPlane.StartEngine("Contact"); myPlane.TakeOff(); myPlane.Drive(); myPlane.StopEngine("Whirr");

Console.WriteLine("\nJourney by car:"); Car myCar = new Car(); myCar.StartEngine("Brm brm"); myCar.Accelerate(); myCar.Drive();

Page 22: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE myCar.Brake(); myCar.StopEngine("Phut phut");

Console.WriteLine("\nTesting polymorphism"); Vehicle v = myCar; v.Drive(); v = myPlane; v.Drive(); }

static void Main() { try { doWork(); } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.Message); } } }}

d)Vehicle.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace Vehicles{ class Vehicle { public void StartEngine(string noiseToMakeWhenStarting) { Console.WriteLine($"Starting engine: {noiseToMakeWhenStarting}"); }

public void StopEngine(string noiseToMakeWhenStopping) { Console.WriteLine($"Stopping engine: {noiseToMakeWhenStopping}"); }

public virtual void Drive() { Console.WriteLine("Default implementation of the Drive method"); } }}

Page 23: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE

C# Program to Demonstrate Defining and Using Interfacesa) circle.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Windows.UI;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Shapes;using Windows.UI.Xaml.Controls;

namespace Drawing{ class Circle : DrawingShape, IDraw, IColor { public Circle(int diameter):base(diameter) { }

public override void Draw(Canvas canvas) { if(this.shape!=null) { canvas.Children.Remove(this.shape); } else { this.shape = new Ellipse(); }

base.Draw(canvas); } }}b)DrawingPad.xaml.csusing System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;

Page 24: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSEusing Windows.UI;

namespace Drawing{ public sealed partial class DrawingPad : Page { public DrawingPad() { this.InitializeComponent(); }

private void drawingCanvas_Tapped(object sender, TappedRoutedEventArgs e) { Point mouseLocation = e.GetPosition(this.drawingCanvas); Square mySquare = new Square(100);

if (mySquare is IDraw) { IDraw drawSquare = mySquare; drawSquare.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y); drawSquare.Draw(drawingCanvas); }

if (mySquare is IColor) { IColor colorSquare = mySquare; colorSquare.SetColor(Colors.BlueViolet); } }

private void drawingCanvas_RightTapped(object sender, RightTappedRoutedEventArgs e) { Point mouseLocation = e.GetPosition(this.drawingCanvas); Circle myCircle = new Circle(100);

if (myCircle is IDraw) { IDraw drawCircle = myCircle; drawCircle.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y); drawCircle.Draw(drawingCanvas); }

if (myCircle is IColor) { IColor colorCircle = myCircle; colorCircle.SetColor(Colors.HotPink); } } }}

Page 25: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSEc)DrawingShape.csusing System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;using Windows.UI;

namespace Drawing{ public sealed partial class DrawingPad : Page { public DrawingPad() { this.InitializeComponent(); }

private void drawingCanvas_Tapped(object sender, TappedRoutedEventArgs e) { Point mouseLocation = e.GetPosition(this.drawingCanvas); Square mySquare = new Square(100);

if (mySquare is IDraw) { IDraw drawSquare = mySquare; drawSquare.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y); drawSquare.Draw(drawingCanvas); }

if (mySquare is IColor) { IColor colorSquare = mySquare; colorSquare.SetColor(Colors.BlueViolet); } }

private void drawingCanvas_RightTapped(object sender, RightTappedRoutedEventArgs e) { Point mouseLocation = e.GetPosition(this.drawingCanvas); Circle myCircle = new Circle(100);

Page 26: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE if (myCircle is IDraw) { IDraw drawCircle = myCircle; drawCircle.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y); drawCircle.Draw(drawingCanvas); }

if (myCircle is IColor) { IColor colorCircle = myCircle; colorCircle.SetColor(Colors.HotPink); } } }}d)IColour.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Windows.UI;

namespace Drawing{ interface IColor { void SetColor(Color color); }}e)IDraw.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Windows.UI.Xaml.Controls;

namespace Drawing{ interface IDraw { void SetLocation(int xCoord, int yCoord); void Draw(Canvas canvas); }}f)Square.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

Page 27: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSEusing Windows.UI;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Shapes;using Windows.UI.Xaml.Controls;

namespace Drawing{ class Square : DrawingShape, IDraw, IColor { public Square(int sideLength):base(sideLength) { }

public override void Draw(Canvas canvas) { if(this.shape!=null) { canvas.Children.Remove(this.shape); } else { this.shape = new Rectangle(); }

base.Draw(canvas); } }}

Implementing Exception-Safe Disposal: Calling the Dispose Method from a Destructor---- We are using IDisposable Interface here which contains Dispose method. Program.cs using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace GarbageCollectionDemo{ class Program { static void Main(string[] args) { using (Calculator calculator = new Calculator()) { Console.WriteLine($"120 / 15 = {calculator.Divide(120, 15)}");

Page 28: pavandm.files.wordpress.com  · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");

C#.NET Programs for 5th Sem CSE }

Console.WriteLine("Program finishing"); Console.ReadLine(); } }}

Calculator.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace GarbageCollectionDemo{ class Calculator : IDisposable { private bool disposed = false; public Calculator() { Console.WriteLine("Calculator being created"); }

~Calculator() { Console.WriteLine("Calculator being finalized"); this.Dispose(); }

public int Divide(int first, int second) { return first / second; }

public void Dispose() { if (!this.disposed) { Console.WriteLine("Calculator being disposed"); }

this.disposed = true; GC.SuppressFinalize(this); } }}

NOTE: THIS SOFTCOPY CONTAINS THE PROGRAM UPTO 3rd MODULE.