· Web viewC# Program to Define automatic properties and use object initializers polygon.cs...

22

Click here to load reader

Transcript of · Web viewC# Program to Define automatic properties and use object initializers polygon.cs...

Page 1: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

1)C# Program to Define automatic properties and use object initializers

a) polygon.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace AutomaticProperties{ class Polygon { public int NumSides { get; set; } public double SideLength { get; set; } public Polygon() { this.NumSides = 4; this.SideLength = 10.0; } }}

b) Program.csusing System;using System.Collections.Generic;using System.Text;

namespace AutomaticProperties{ class Program { static void doWork() { Polygon square = new Polygon(); Polygon triangle = new Polygon { NumSides = 3 }; Polygon pentagon = new Polygon { SideLength = 15.5, NumSides = 5 };

Console.WriteLine($"Square: number of sides is {square.NumSides}, length of each side is {square.SideLength}"); Console.WriteLine($"Triangle: number of sides is {trianngle.NumSides}, length of each side is {triangle.SideLength}"); Console.WriteLine($"Pentagon: number of sides is {pentagon.NumSides}, length of each side is {pentagon.SideLength}"); }

static void Main(string[] args) {

Page 2: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

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

2)C# Program on creating square and circle object on the canvas using Properties(Drawing pad program)

a)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;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.X = (int)mouseLocation.X;

Page 3: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

drawSquare.Y = (int)mouseLocation.Y; drawSquare.Draw(drawingCanvas); }

if (mySquare is IColor) { IColor colorSquare = mySquare; colorSquare.Color = 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.X = (int)mouseLocation.X; drawCircle.Y = (int)mouseLocation.Y; drawCircle.Draw(drawingCanvas); }

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

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

namespace Drawing{ abstract class DrawingShape { protected int _size; protected int _x = 0, _y = 0; protected Shape shape = null;

public DrawingShape(int size) {

Page 4: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

this._size = size; }

public int X { get { return this._x; } set { this._x = value; } }

public int Y { get { return this._y; } set { this._y = value; } }

public Color Color { set { if (this.shape != null) { SolidColorBrush brush = new SolidColorBrush(value); this.shape.Fill = brush; } } } public virtual void Draw(Canvas canvas) { if(this.shape == null) { throw new InvalidOperationException("Shape is null"); }

this.shape.Height = this._size; this.shape.Width = this._size; Canvas.SetTop(this.shape, this._y); Canvas.SetLeft(this.shape, this._x); canvas.Children.Add(this.shape); } } }

c)IColour.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Windows.UI;

namespace Drawing{ interface IColor

Page 5: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

{ Color Color { set; } }}

d)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 { int X { get; set; } int Y { get; set; } void Draw(Canvas canvas); }}e)Square.csusing 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 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); } }

Page 6: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

}

3)C# Program on Indexer

a)Program.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace Indexer{ class Program { static void Main(string[] args) { Employee emp = new Employee(1001, 20000.00, "john", "Manager", "Sales", "Mumbai"); Console.WriteLine("Employee Number is :" + emp[0]); Console.WriteLine("Employee Salary is :" + emp[1]); Console.WriteLine("Employee Name is :" + emp[2]); Console.WriteLine("Employee Job is :" + emp[3]); Console.WriteLine("Employee Dname is :" + emp[4]); Console.WriteLine("Employee Location is :" + emp[5]); emp[2] = "Shawn"; emp[0] = 2001; emp[1] = 20000.00; emp[5] = "Bangaluru";

Console.WriteLine("Modified Values are"); Console.WriteLine("Employee Number is :" + emp[0]); Console.WriteLine("Employee Salary is :" + emp[1]); Console.WriteLine("Employee Name is :" + emp[2]); Console.WriteLine("Employee Job is :" + emp[3]); Console.WriteLine("Employee Dname is :" + emp[4]); Console.WriteLine("Employee Location is :" + emp[5]);

Console.ReadLine(); }

}}

b) Employee.cs

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

Page 7: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

namespace Indexer{ class Employee { int Eno; double Salary; string Ename, job, Dname, Location; public Employee(int Eno,double Salary,string Ename, string job, string Dname,string Location)

{ this.Eno = Eno; this.Salary = Salary; this.Ename = Ename; this.job = job; this.Dname = Dname; this.Location = Location;

} public object this[int index] { get { if (index==0) return Eno; else if (index==1) return Salary; else if (index==2) return Ename; else if (index==3) return job; else if (index==4) return Dname; else if (index==5) return Location; return null; } set { if (index==0) Eno = (int)value; else if (index == 1) Salary = (double)value; else if (index== 2) Ename =(string)value; else if (index==3) job = (string)value; else if (index==4) Dname = (string)value; else if (index==5) Location = (string)value; } }

Page 8: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

} }

4)Building Binary tree Class by using Generics to sort the item (Example of Generics)BinaryTree(tree.cs)using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace BinaryTree{ public class Tree<TItem> where TItem : IComparable<TItem> { public TItem NodeData { get; set; } public Tree<TItem> LeftTree { get; set; } public Tree<TItem> RightTree { get; set; }

public Tree(TItem nodeValue) { this.NodeData = nodeValue; this.LeftTree = null; this.RightTree = null; }

public void Insert(TItem newItem) { TItem currentNodeValue = this.NodeData; if (currentNodeValue.CompareTo(newItem) > 0) { // Insert the item into the left subtree if (this.LeftTree == null) { this.LeftTree = new Tree<TItem>(newItem); } else { this.LeftTree.Insert(newItem); } } else { // Insert the new item into the right subtree if (this.RightTree == null) { this.RightTree = new Tree<TItem>(newItem); } else {

Page 9: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

this.RightTree.Insert(newItem); } } }

public string WalkTree() { string result = "";

if (this.LeftTree != null) { result = this.LeftTree.WalkTree(); }

result += $" {this.NodeData.ToString()} ";

if (this.RightTree != null) { result += this.RightTree.WalkTree(); }

return result; }

}}

2.BinarTreeTest program.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using BinaryTree;

namespace BinaryTreeTest{ class Program { static void Main(string[] args) { Tree<int> tree1 = new Tree<int>(10); tree1.Insert(5); tree1.Insert(11); tree1.Insert(5); tree1.Insert(-12); tree1.Insert(15); tree1.Insert(0); tree1.Insert(14); tree1.Insert(-8); tree1.Insert(10); tree1.Insert(8); tree1.Insert(8);

string sortedData = tree1.WalkTree();

Page 10: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

Console.WriteLine($"Sorted data is: {sortedData}");

Tree<string> tree2 = new Tree<string>("Hello"); tree2.Insert("World"); tree2.Insert("How"); tree2.Insert("Are"); tree2.Insert("You"); tree2.Insert("Today"); tree2.Insert("I"); tree2.Insert("Hope"); tree2.Insert("You"); tree2.Insert("Are"); tree2.Insert("Feeling"); tree2.Insert("Well"); tree2.Insert("!");

sortedData = tree2.WalkTree(); Console.WriteLine($"Sorted data is: {sortedData}"); } }}

BuildTree (Sorting Character Data) program.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using BinaryTree;

namespace BuildTree{ class Program { static void Main(string[] args) { Tree<char> charTree = null; InsertIntoTree<char>(ref charTree, 'M', 'X', 'A', 'M', 'Z', 'Z', 'N'); string sortedData = charTree.WalkTree(); Console.WriteLine($"Sorted data is {sortedData}"); }

static void InsertIntoTree<TItem>(ref Tree<TItem> tree, params TItem[] data) where TItem : IComparable<TItem> { foreach(TItem datum in data) { if(tree==null) { tree = new Tree<TItem>(datum); } else {

Page 11: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

tree.Insert(datum); } } } }}

5) Programming Example on List<T> Collection Classusing System;using System.Collections.Generic;using System.Text;namespace Listexample{ class Program { static void Main(string[] args) { List<int> numbers = new List<int>(); foreach (int number in new int[12]{10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1}) { numbers.Add(number); }

// The first parameter is the position; the second parameter is the value being inserted numbers.Insert(numbers.Count-1, 99);

// Remove first element whose value is 7 (the 4th element, index 3) numbers.Remove(7);

// Remove the element that's now the 7th element, index 6 (10)

numbers.RemoveAt(6);

// Iterate remaining 11 elements using a for statement

Console.WriteLine("Iterating using a for statement:"); for (int i = 0; i < numbers.Count; i++) { int number = numbers[i];

// Note the use of array syntax

Console.WriteLine(number); }

// Iterate the same 11 elements using a foreach statement

Console.WriteLine("\nIterating using a foreach statement:"); foreach (int number in numbers) { Console.WriteLine(number); } Console.Read(); } }}

Page 12: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

6)Programming Example for LinkedList<T> Collection classusing System;using System.Collections.Generic;.Class mainclass{ LinkedList<int> numbers = new LinkedList<int>();// Fill the List<int> by using the AddFirst methodforeach (int number in new int[] { 10, 8, 6, 4, 2 }){ numbers.AddFirst(number);}// Iterate using a for statementConsole.WriteLine("Iterating using a for statement:");for (LinkedListNode<int> node = numbers.First; node != null; node = node.Next){ int number = node.Value; Console.WriteLine(number);}// Iterate using a foreach statementConsole.WriteLine("\nIterating using a foreach statement:");foreach (int number in numbers){ Console.WriteLine(number);}// Iterate backwardsConsole.WriteLine("\nIterating list in reverse order:");for (LinkedListNode<int> node = numbers.Last; node != null; node = node.Previous){ int number = node.Value; Console.WriteLine(number);}

}

7)Program on Queue<T> Collection Classusing System;using System.Collections.Generic;Class mainclass{ Public static void Main(){

Queue<int> numbers = new Queue<int>();// fill the queueConsole.WriteLine("Populating the queue:");foreach (int number in new int[4]{9, 3, 7, 2}){

numbers.Enqueue(number); Console.WriteLine("{0} has joined the queue", number);

}// iterate through the queueConsole.WriteLine("\nThe queue contains the following items:");foreach (int number in numbers)

Page 13: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

{ Console.WriteLine(number); }

// empty the queueConsole.WriteLine("\nDraining the queue:");while (numbers.Count > 0){

int number = numbers.Dequeue(); Console.WriteLine("{0} has left the queue", number);}

}}

8 Program on stack<T> Collection Classusing System;using System.Collections.Generic;Class mainapp{ public static void Main(){Stack<int> numbers = new Stack<int>(); Console.WriteLine("Pushing items onto the stack:");foreach (int number in new int[4]{9, 3, 7, 2}){ numbers.Push(number); Console.WriteLine("{0} has been pushed on the stack", number);}Console.WriteLine("\nThe stack now contains:"); // iterate through the stackforeach (int number in numbers){ Console.WriteLine(number);}Console.WriteLine("\nPopping items from the stack:"); // empty the stackwhile (numbers.Count > 0){ int number = numbers.Pop(); Console.WriteLine("{0} has been popped off the stack", number);}}}

9 Program on The Dictionary<TKey, TValue> Collection Classusing System.Collections.Generic;Class mainApp{ public static void Main(){Dictionary<string, int> ages = new Dictionary<string, int>();// fill the Dictionaryages.Add("John", 47); // using the Add methodages.Add("Diana", 46);ages["James"] = 20; // using array notationages["Francesca"] = 18; // iterate using a foreach statement// the iterator generates a KeyValuePair item

Page 14: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

Console.WriteLine("The Dictionary contains:");foreach (KeyValuePair<string, int> element in ages){ string name = element.Key; int age = element.Value; Console.WriteLine("Name: {0}, Age: {1}", name, age);}}}

10 Program on SortedList<TKey, TValue> Collection Class using System.Collections.Generic;Class mainApp{ public static void Main(){SortedList<string, int> ages = new SortedList<string, int>( )// fill the Dictionaryages.Add("John", 47); // using the Add methodages.Add("Diana", 46);ages["James"] = 20; // using array notationages["Francesca"] = 18; // iterate using a foreach statement// the iterator generates a KeyValuePair itemConsole.WriteLine("The Sorted List contains:");foreach (KeyValuePair<string, int> element in ages){ string name = element.Key; int age = element.Value; Console.WriteLine("Name: {0}, Age: {1}", name, age);}}}

11 Program on HashSet<T> Collection Classusing System;using System.Collections.Generic;Class mainapp { Public static void Main() { HashSet<string> employees = new HashSet<string>(new string[] {"Fred","Bert","Harry","John"});HashSet<string> customers = new HashSet<string>(new string[] {"John","Sid","Harry","Diana"});employees.Add("James"); customers.Add("Francesca")Console.WriteLine("Employees:");foreach (string name in employees){ Console.WriteLine(name);}Console.WriteLine("\nCustomers:");foreach (string name in customers){ Console.WriteLine(name);

Page 15: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

}Console.WriteLine("\nCustomers who are also employees:");customers.IntersectWith(employees);foreach (string name in customers){ Console.WriteLine(name);} } }

12 Program on Operator Overloading…. Complex Numbers(Addition, Substraction, Multiplication, Division, Equal to and Not Equal to Etc)

1.ComplexNumbersa)Complex.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace ComplexNumbers{ class Complex { public int Real { get; set; } public int Imaginary { get; set; }

public Complex(int real, int imaginary) { this.Real = real; this.Imaginary = imaginary; }

public Complex(int real) { this.Real = real; this.Imaginary = 0; }

public static implicit operator Complex(int from) { return new Complex(from); }

public static explicit operator int(Complex from) {

Page 16: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

return from.Real; }

public override string ToString() { return $"({this.Real} + {this.Imaginary}i)"; }

public static Complex operator +(Complex lhs, Complex rhs) { return new Complex(lhs.Real + rhs.Real, lhs.Imaginary + rhs.Imaginary); }

public static Complex operator -(Complex lhs, Complex rhs) { return new Complex(lhs.Real - rhs.Real, lhs.Imaginary - rhs.Imaginary); }

public static Complex operator *(Complex lhs, Complex rhs) { return new Complex(lhs.Real * rhs.Real - lhs.Imaginary * rhs.Imaginary, lhs.Imaginary * rhs.Real + lhs.Real * rhs.Imaginary); }

public static Complex operator /(Complex lhs, Complex rhs) { int realElement = (lhs.Real * rhs.Real + lhs.Imaginary * rhs.Imaginary) / (rhs.Real * rhs.Real + rhs.Imaginary * rhs.Imaginary);

int imaginaryElement = (lhs.Imaginary * rhs.Real - lhs.Real * rhs.Imaginary) / (rhs.Real * rhs.Real + rhs.Imaginary * rhs.Imaginary);

return new Complex(realElement, imaginaryElement); }

public static bool operator ==(Complex lhs, Complex rhs) { return lhs.Equals(rhs); }

public static bool operator !=(Complex lhs, Complex rhs) { return !(lhs.Equals(rhs)); }

public override bool Equals(object obj) { if(obj is Complex) { Complex compare = (Complex)obj; return (this.Real == compare.Real) && (this.Imaginary == compare.Imaginary); } else

Page 17: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

{ return false; } }

public override int GetHashCode() { return base.GetHashCode(); } }}

b)program.csusing System;

namespace ComplexNumbers{ class Program { static void doWork() { Complex first = new Complex(10, 4); Complex second = new Complex(5, 2);

Console.WriteLine($"first is {first}"); Console.WriteLine($"second is {second}");

Complex temp = first + second; Console.WriteLine($"Add: result is {temp}");

temp = first - second; Console.WriteLine($"Subtract: result is {temp}");

temp = first * second; Console.WriteLine($"Multiply: result is {temp}");

temp = first / second; Console.WriteLine($"Divide: result is {temp}");

if(temp == first) { Console.WriteLine("Comparison: temp == first"); } else { Console.WriteLine("Comparison: temp != first"); }

if(temp == temp) { Console.WriteLine("Comparison: temp == temp"); } else

Page 18: · Web viewC# Program to Define automatic properties and use object initializers polygon.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using

{ Console.WriteLine("Comparison: temp != temp"); }

Console.WriteLine($"Current value of temp is {temp}");

if(temp==2) { Console.WriteLine("Comparison after conversion: temp == 2"); } else { Console.WriteLine("Comparison after conversion: temp != 2"); }

temp += 2; Console.WriteLine($"Value after adding 2: temp = {temp}");

int tempInt = (int)temp; Console.WriteLine($"Int value after conversion: tempInt == {tempInt}"); }

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