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();
35
Embed
pavandm.files.wordpress.com · Web viewHello world program: TestHello.cs. namespace TestHello { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!");
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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(); }
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;
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();
C#.NET Programs for 5th Sem CSE break; case "string": showStringValue(); break; case "char": showCharValue(); break; case "bool": showBoolValue(); break; } }
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 int dateCompare(DateTime leftHandSide, DateTime rightHandSide) { int result = 0;
if (leftHandSide.Year < rightHandSide.Year) { result = -1; } else if (leftHandSide.Year > rightHandSide.Year) {
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;
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
// 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];
C#.NET Programs for 5th Sem CSE copyOne(current); } }
private void copyOne(char current) { switch (current) { case '<': target.Text += "<"; break; case '>': target.Text += ">"; break; case '&': target.Text += "&"; break; case '\"': target.Text += """; break; case '\'': target.Text += "'"; break; default: target.Text += current; break; }
8. C# Program to Demonstrate the Working of While Statement
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(); }
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()}"); }
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
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); }
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);
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}"); }
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); } } }
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); }
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)}"); } }
namespace Extensions{ static class Util { public static int ConvertToBase(this int i, int baseToConvertTo) {
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
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);
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;
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)}");