+ All Categories
Home > Documents > C# Walk Through - 1

C# Walk Through - 1

Date post: 07-Apr-2018
Category:
Upload: ranjan2130
View: 221 times
Download: 0 times
Share this document with a friend

of 14

Transcript
  • 8/3/2019 C# Walk Through - 1

    1/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 1 of14

    Try Following Programs in Visual Studio using C#. Following material is given to you for practice only.

    1. // Demonstrating Simple Programusing System;namespace Test{

    classProgram{

    staticvoid Main(string[] args)

    {int myInteger;string myString;myInteger = 17;myString = "\"myInteger\" is";Console.WriteLine("{0} {1}.", myString, myInteger);Console.ReadKey();

    }}

    }2. // Demonstrating Type Conversions

    using System;namespace Test{

    classProgram{

    staticvoid Main(string[] args){

    double firstNumber, secondNumber;string userName;Console.WriteLine("Enter your name:");userName = Console.ReadLine();Console.WriteLine("Welcome {0}!", userName);Console.WriteLine("Now give me a number:");firstNumber = Convert.ToDouble(Console.ReadLine());Console.WriteLine("Now give me another number:");secondNumber = Convert.ToDouble(Console.ReadLine());Console.WriteLine("The sum of {0} and {1} is {2}.", firstNumber,

    secondNumber, firstNumber + secondNumber);Console.WriteLine("The result of subtracting {0} from {1} is {2}.",secondNumber, firstNumber, firstNumber - secondNumber);Console.WriteLine("The product of {0} and {1} is {2}.", firstNumber,secondNumber, firstNumber * secondNumber);Console.WriteLine("The result of dividing {0} by {1} is {2}.",firstNumber, secondNumber, firstNumber / secondNumber);Console.WriteLine("The remainder after dividing {0} by {1} is {2}.",firstNumber, secondNumber, firstNumber % secondNumber);Console.ReadKey();

    }}

    }

    3. // Demonstrating Operations

    using System;namespace Test{

    classProgram{

    staticvoid Main(string[] args){

    Console.WriteLine("Enter an integer:");int myInt = Convert.ToInt32(Console.ReadLine());bool isLessThan10 = myInt < 10;bool isBetween0And5 = (0

  • 8/3/2019 C# Walk Through - 1

    2/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 2 of14

    using System;namespace Test{

    classProgram{

    staticvoid Main(string[] args){

    string comparison;Console.WriteLine("Enter a number:");

    double var1 = Convert.ToDouble(Console.ReadLine());Console.WriteLine("Enter another number:");double var2 = Convert.ToDouble(Console.ReadLine());if (var1 < var2)

    comparison = "less than";else{

    if (var1 == var2)comparison = "equal to";

    elsecomparison = "greater than";

    }Console.WriteLine("The first number is {0} the second number." ,

    comparison);

    Console.ReadKey();}}

    }

    5. // Demonstrating Switch.using System;namespace Test{

    classProgram{

    staticvoid Main(string[] args){

    conststring myName = "ram";conststring popularName = "amitabh";conststring sillyName = "humpty";string name;Console.WriteLine("What is your name?");name = Console.ReadLine();Console.WriteLine("Hello {0}!", name);switch (name.ToLower()){

    case myName:Console.WriteLine("You have the same name as me!");break;

    case popularName:Console.WriteLine("Hey, what a Popular name you have!");break;

    case sillyName:Console.WriteLine("That's a very silly name.");break;

    default:Console.WriteLine("That's a unique name.");break;

    }Console.ReadKey();

    }}

    }

    6. // Demonstrating Interest Calculation.using System;namespace Test{

    classProgram{

    staticvoid Main(string[] args){

    double balance, interestRate, targetBalance;

  • 8/3/2019 C# Walk Through - 1

    3/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 3 of14

    Console.WriteLine("What is your current deposits?");balance = Convert.ToDouble(Console.ReadLine());Console.WriteLine("What is your annual interest rate (in %)?");interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;Console.WriteLine("What maturity amount would you like to have?");targetBalance = Convert.ToDouble(Console.ReadLine());int totalYears = 0;do{

    balance *= interestRate;++totalYears;}while (balance < targetBalance);Console.WriteLine("In {0} year{1} you'll have a amount of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);Console.ReadKey();

    }}

    }

    7. // Demonstrating Date & Time formats.using System;usingC = System.Console;namespace Test

    { classProgram{

    staticvoid Main(string[] args){

    DateTime dateTime = DateTime.Now; // invoking Current System Date.C.WriteLine("d = {0:d}", dateTime); // mm/dd/yyyyC.WriteLine("D = {0:D}", dateTime); // month dd, yyyyC.WriteLine("f = {0:f}", dateTime); // day, month dd, yyyy hh:mmC.WriteLine("F = {0:F}", dateTime); // day,month dd,yyyy HH:mm:ss

    AM/PMC.WriteLine("g = {0:g}", dateTime); // mm/dd/yyyy HH:mmC.WriteLine("G = {0:G}", dateTime); // mm/dd/yyyy hh:mm:ssC.WriteLine("M = {0:M}", dateTime); // month ddC.WriteLine("R = {0:R}", dateTime); // ddd Month yyyy hh:mm:ss GMTC.WriteLine("s = {0:s}", dateTime); // yyyy-mm-dd hh:mm:ss (Sortable)C.WriteLine("t = {0:t}", dateTime); // hh:mm AM/PMC.WriteLine("T = {0:T}", dateTime); // hh:mm:ss AM/PMC.WriteLine("u = {0:u}", dateTime); // yyyy-mm-dd hh:mm:ss (Sortable)C.WriteLine("U = {0:U}", dateTime); // day, month dd, yyyy hh:mm:ss

    AM/PMC.WriteLine("Y = {0:Y}", dateTime); // month, yyyy (March, 2006)C.WriteLine("Month = " + dateTime.Month); // month number (3)C.WriteLine("Day Of Week = " + dateTime.DayOfWeek); // day of week name

    (Friday)C.WriteLine("Time Of Day = " + dateTime.TimeOfDay); // 24 hour time

    (16:12:11)// Ticks are no of 100 nanosecond intervals since 01/01/000112:00am// Ticks are useful in elapsed time measurement.C.WriteLine("DateTime.Ticks = " + dateTime.Ticks);

    }}

    }

    8. // Demonstrating String Methods.using System;namespace Test{

    classProgram{

    staticvoid Main(){

    char[] characterArray;int position;

    string result, string1;string1 = "The education of Cissy!";characterArray = newchar[30];// create the output stringresult = "string = \"" + string1 + "\"";

  • 8/3/2019 C# Walk Through - 1

    4/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 4 of14

    // Length propertyresult += "\nstring length = " + string1.Length;// IndexOf method (returns -1 if not found)position = string1.IndexOf("e");result += "\nstring contains an 'e' at index: "+ position;// find another "e"position = string1.IndexOf("e", position + 1);result += "\nstring contains a second 'e' at index: "+ position;// Search/Find a substring (returns True or False)

    if (string1.Contains("Cissy"))result += "\nstring contains 'Cissy'->"+ string1.Contains("Cissy");// Search/Find a substring positionposition = string1.IndexOf("Cissy");result += "\n'Cissy' starts at index: "+ position;// change case of stringresult += "\nlower case string: \""+ string1.ToLower() + "\"";result += "\nupper case string: \""+ string1.ToUpper() + "\"";// indexing, loop through characters// in string1 and display in reverse orderresult += "\nreverse string: \"";for (int i = string1.Length - 1; i >= 0; i--){

    result += string1[i];

    }// Replace methodresult += "\"\nreplace 'educ' with 'matur': ";result += "\"" + string1.Replace("educ", "matur") + "\"";// Use the CopyTo method to copy characters// from string1 into characterArraystring1.CopyTo(0, characterArray, 0, 6);result += "\nFirst 6 characters of array contain: \"";// display arrayfor (int i = 0; i < 6; i++){

    result += characterArray[i];}Console.WriteLine(result +"\"\n\n(Press \"Enter\" to exit.)");Console.Read();

    }}

    }

    9. // Simple interest calculation table.using System;namespace Test{

    classProgram{

    staticvoid Main(){

    Console.Write("Enter principal amount: ");decimal principal = Convert.ToDecimal(Console.ReadLine());if (principal < 0) // principal cannot be negative{

    Console.WriteLine("Principal cannot be negative");principal = 0;

    }Console.Write("Enter interest rate : ");decimal interest = Convert.ToDecimal(Console.ReadLine());if (interest < 0) // interest cannot be negative{

    Console.WriteLine("Interest cannot be negative");interest = 0;

    }Console.Write("Enter number of years : ");int noYears = Convert.ToInt32(Console.ReadLine());Console.WriteLine("\nPrincipal = " + principal

    + "\nInterest = " + interest + "%"+ "\nDuration = " + noYears + " years\n");

    int year = 1;while (year

  • 8/3/2019 C# Walk Through - 1

    5/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 5 of14

    decimal interestPaid = principal * (interest / 100); // calculateinterest

    principal += interestPaid; // calculate new principalprincipal = decimal.Round(principal, 2); // round to the nearest

    pennyConsole.WriteLine("Year " + year + " Rs. " + principal);year++;

    }Console.WriteLine("\nPress Enter to stop");

    Console.ReadKey();}}

    }

    10. // Measuring Time of execution in a task Method 1using System;namespace Test{

    classProgram{

    staticvoid Main(){

    DateTime startTime = DateTime.Now;Console.WriteLine("Started: {0}", startTime);

    // Execute the task to be timedfor (int i = 1; i < 100000; i++) { }DateTime stopTime = DateTime.Now;Console.WriteLine("Stopped: {0}", stopTime);TimeSpan elapsedTime = stopTime - startTime;Console.WriteLine("Elapsed: {0}", elapsedTime);Console.WriteLine("in hours :" + elapsedTime.TotalHours);Console.WriteLine("in minutes :" + elapsedTime.TotalMinutes);Console.WriteLine("in seconds :" + elapsedTime.TotalSeconds);Console.WriteLine("in milliseconds:" + elapsedTime.TotalMilliseconds);Console.ReadKey();

    }}

    }

    11. // Measuring Time of execution in a task Method 2using System;using System.Diagnostics;namespace Test{

    classProgram{

    staticvoid Main(){

    Stopwatch watch = newStopwatch();watch.Start();for (int i = 1; i < 1000000; i++) { } // Execute the task to be timedwatch.Stop();

    Console.WriteLine("Elapsed: {0}", watch.Elapsed);Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds);Console.WriteLine("In timer ticks: {0}", watch.ElapsedTicks);Console.ReadKey();

    }}

    }

    12. // Sorting Array elementsusing System;namespace Test{

    publicclassProgram{

    staticvoid Main(string[] args){

    string[] strings = { "beta", "theta", "gamma", "alpha" };Console.WriteLine("Array elements: ");DisplayArray(strings);Array.Sort(strings);DisplayArray(strings);

  • 8/3/2019 C# Walk Through - 1

    6/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 6 of14

    }publicstaticvoid DisplayArray(Array array){

    foreach (object o in array){

    Console.Write("{0} ", o);}Console.WriteLine();

    }

    }}

    13. // Reverse Array element orderusing System;namespace Test{

    publicclassProgram{

    staticvoid Main(string[] args){

    string[] strings = { "alpha", "beta", "gamma" };Console.WriteLine("Array elements: ");DisplayArray(strings);Array.Reverse(strings);

    DisplayArray(strings);}publicstaticvoid DisplayArray(Array array){

    foreach (object o in array){

    Console.Write("{0} ", o);}Console.WriteLine();

    }}

    }

    14. // demonstrating class access modifiersusing System;namespace Test{

    classCar{

    // declare the fieldspublicstring make;protectedinternalstring model;internalstring color;protectedint horsepower = 150;privateint yearBuilt;// define the methodspublicvoid SetYearBuilt(int yearBuilt){

    yearBuilt = yearBuilt;}publicint GetYearBuilt(){

    return yearBuilt;}publicvoid Start(){

    Console.WriteLine("Starting car ...");TurnStarterMotor();System.Console.WriteLine("Car started");

    }privatevoid TurnStarterMotor(){

    Console.WriteLine("Turning starter motor ...");}

    }publicclassExample{

    publicstaticvoid Main(){

  • 8/3/2019 C# Walk Through - 1

    7/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 7 of14

    // create a Car objectCar myCar = newCar();// assign values to the Car object fieldsmyCar.make = "Toyota";myCar.model = "MR2";myCar.color = "black";// myCar.horsepower = 200; // protected field not accessible// myCar.yearBuilt = 1995; // private field not accessible// call the SetYearBuilt() method to set the private yearBuilt field

    myCar.SetYearBuilt(1995);// display the values for the Car object fieldsConsole.WriteLine("myCar.make = " + myCar.make);Console.WriteLine("myCar.model = " + myCar.model);Console.WriteLine("myCar.color = " + myCar.color);// call the GetYearBuilt() method to get the private yearBuilt fieldConsole.WriteLine("myCar.GetYearBuilt() = " + myCar.GetYearBuilt());myCar.Start();// call the Start() method// myCar.TurnStarterMotor(); // private method not accessible

    }}

    }

    15. //Constructor, static constructor & destructorusing System;

    namespace Test{classTest2{

    staticint i;static Test2(){

    i = 4;Console.Out.WriteLine("inside static construtor...");

    }public Test2(){

    Console.Out.WriteLine("inside regular construtor... i={0}", i);}~Test2(){

    Console.Out.WriteLine("inside destructor");}staticvoid Main(string[] args){

    Console.Out.WriteLine("Test2");newTest2();newTest2();

    }}

    }

    16. //Calling non virtualusing System;namespace Test{

    classPlane{

    publicdouble TopSpeed(){

    return 300.0D;}

    }classJet : Plane{

    publicdouble TopSpeed(){

    return 900.0D;}

    }classAirport{

    staticvoid Main(string[] args){

  • 8/3/2019 C# Walk Through - 1

    8/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 8 of14

    Plane plane = newJet();Console.WriteLine("planes top speed: {0}", plane.TopSpeed());Console.ReadLine();

    }}

    }

    The out put will be planes top speed: 300.0This, will print "300" for the planes speed, since TopSpeed() is not virtual. Tofix the problem we need to declare the method virtual *and* that the derived

    "override"s the method. If we don't set Jet's method to override, we still get"300")

    17. //Calling virtual solution to program 15.using System;namespace Test{

    classPlane{

    publicvirtualdouble TopSpeed(){

    return 300.0D;}

    }classJet : Plane

    {publicoverridedouble TopSpeed(){

    return 900.0D;}

    }classAirport{

    staticvoid Main(string[] args){

    Plane plane = newJet();Console.WriteLine("planes top speed: {0}", plane.TopSpeed());Console.ReadLine();

    }

    }}

    The out put will be planes top speed: 900.0

    18. using System;namespace Test{

    classPlane{

    publicvirtualdouble TopSpeed(){

    return 300.0D;}

    }classJet : Plane

    {publicoverridedouble TopSpeed(){

    return 900.0D;}

    }classAirport{

    staticvoid Main(string[] args){

    Plane plane = newJet();Console.WriteLine("plane's top speed: {0}", plane.TopSpeed());Jet jet = newJet();Console.WriteLine("jet's top speed: {0}", jet.TopSpeed());

    Console.ReadLine();}

    }}

    The out put will be

  • 8/3/2019 C# Walk Through - 1

    9/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 9 of14

    planes top speed: 900.0jet's top speed: 900.0

    19. using System;namespace Test{

    classPlane{

    publicvirtualdouble TopSpeed(){

    return 300.0D;}

    }classJet : Plane{

    publicoverridedouble TopSpeed(){

    return 900.0D;}

    }classAirport{

    staticvoid Main(string[] args){

    Plane plane = newPlane();Console.WriteLine("plane's top speed: {0}", plane.TopSpeed());Jet jet = newJet();Console.WriteLine("jet's top speed: {0}", jet.TopSpeed());Console.ReadLine();

    }}

    }

    The out put will beplanes top speed: 300.0jet's top speed: 900.0

    20. // Demostrates the use of an abstract classusing System;namespace Test

    {publicclassMainClass{

    publicstaticvoid Main(string[] strings){

    SavingsAccount sa = newSavingsAccount();sa.Withdrawal(100);CheckingAccount ca = newCheckingAccount();ca.Withdrawal(100);

    }}abstractpublicclassBankAccount{

    abstractpublicvoid Withdrawal(double dWithdrawal);

    }publicclassSavingsAccount : BankAccount{

    overridepublicvoid Withdrawal(double dWithdrawal){

    Console.WriteLine("Call to SavingsAccount.Withdrawal()");}

    }

    publicclassCheckingAccount : BankAccount{

    overridepublicvoid Withdrawal(double dWithdrawal){

    Console.WriteLine("Call to CheckingAccount.Withdrawal()");

    }}}

    21. //Read comments in the program carefully// Demostrates the use of an abstract class, including an abstract method and// abstract properties.

  • 8/3/2019 C# Walk Through - 1

    10/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 10 of14

    using System;namespace nsAbstract{

    publicclassAbstractclsMain{

    staticvoid Main(string[] args){

    // Create an instance of the derived class.clsDerived derived = newclsDerived(3.14159);

    // Calling GetAbstract() actually calls the public method in the// base class. There is no GetAbstract() in the derived class.derived.GetAbstract();

    }}// Declare an abstract classabstractclassclsBase{

    // Declare an abstract method. Note the semicolon to end the declarationabstractpublicvoid Describe();// Declare an abstract property that has only a get accessor.// Note that you// do not prove the braces for the accessorabstractpublicdouble DoubleProp

    { get;}// Declare an abstract property that has only a set accessor.abstractpublicint IntProp{

    set;}// Declare an abstract propety that has both get and set accessors. Note// that neither the get or set accessor may have a body.abstractpublicstring StringProp{

    get;set;

    }// Declare a method that will access the abstract members.publicvoid GetAbstract(){

    // Get the DoubleProp, which will be in the derived class.Console.WriteLine("DoubleProp = " + DoubleProp);// You can only set the IntProp value. The storage is in the// derived class.IntProp = 42;

    // Set the StringProp valueStringProp = "StringProperty actually is stored in " +

    "the derived class.";// Now show StringPropConsole.WriteLine(StringProp);

    // Finally, call the abstract methodDescribe();

    }}// Derive a class from clsBase. You must implement the abstract membersclassclsDerived : clsBase{

    // Declare a constructor to set the DoubleProp memberpublic clsDerived(double val){

    m_Double = val;}// When you implement an abstract member in a derived class, you may not

    // change the type or access level.overridepublicvoid Describe(){

    Console.WriteLine("You called Describe() from the base " +"class but the code body is in the \r\n" +

  • 8/3/2019 C# Walk Through - 1

    11/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 11 of14

    "derived class");Console.WriteLine("m_Int = " + m_Int);

    }

    // Implement the DoubleProp property. This is where you provide a body// for the accessors.overridepublicdouble DoubleProp{

    get { return (m_Double); }

    }// Implement the set accessor for IntProp.overridepublicint IntProp{

    set { m_Int = value; }}

    // Implement StringProp, providing a body for both the get// and set accessors.overridepublicstring StringProp{

    get { return (m_String); }set { m_String = value; }

    }

    // Declare fields to support the properties.privatedouble m_Double;privateint m_Int;privatestring m_String;

    }}

    22. // Demonstrating class example using inheritanceusing System;namespace test{

    classVehicle{

    int pri_passengers; // number of passengersint pri_fuelcap; // fuel capacity in gallonsint pri_mpg; // fuel consumption in miles per gallon// This is a constructor for Vehicle.public Vehicle(int p, int f, int m){

    passengers = p;fuelcap = f;mpg = m;

    }// Return the range.publicint range(){

    return mpg * fuelcap;}// Compute fuel needed for a given distance.publicdouble fuelneeded(int miles){

    return (double)miles / mpg;}// Propertiespublicint passengers{

    get { return pri_passengers; }set { pri_passengers = value; }

    }publicint fuelcap{

    get { return pri_fuelcap; }set { pri_fuelcap = value; }

    }publicint mpg{

    get { return pri_mpg; }set { pri_mpg = value; }

  • 8/3/2019 C# Walk Through - 1

    12/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 12 of14

    }}// Use Vehicle to create a Truck specialization.classTruck : Vehicle{

    int pri_cargocap; // cargo capacity in pounds// This is a constructor for Truck.public Truck(int p, int f, int m, int c)

    : base(p, f, m)

    { cargocap = c;}// Property for cargocap.publicint cargocap{

    get { return pri_cargocap; }set { pri_cargocap = value; }

    }}publicclassTruckDemo{

    publicstaticvoid Main(){

    // construct some trucksTruck semi = newTruck(2, 200, 7, 44000);Truck pickup = newTruck(3, 28, 15, 2000);double gallons;int dist = 252;gallons = semi.fuelneeded(dist);Console.WriteLine("Semi can carry " + semi.cargocap +

    " pounds.");Console.WriteLine("To go " + dist + " miles semi needs " +

    gallons + " gallons of fuel.\n");gallons = pickup.fuelneeded(dist);Console.WriteLine("Pickup can carry " + pickup.cargocap +

    " pounds.");Console.WriteLine("To go " + dist + " miles pickup needs " +

    gallons + " gallons of fuel.");}

    }}

    23. // Demonstrating method overloadingusing System;namespace test{

    // declare the Swapper classclassSwapper{

    // this Swap() method swaps two int parameterspublicvoid Swap(refint x, refint y){

    int temp = x;x = y;y = temp;

    }

    // this Swap() method swaps two float parameterspublicvoid Swap(reffloat x, reffloat y){

    float temp = x;x = y;y = temp;

    }

    }

    publicclassProgram{

    publicstaticvoid Main(){

  • 8/3/2019 C# Walk Through - 1

    13/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS.NET Walk Through 1 / Page 13 of14

    // create a Swapper objectSwapper mySwapper = newSwapper();

    // declare two int variablesint intValue1 = 2;int intValue2 = 5;System.Console.WriteLine("initial intValue1 = " + intValue1 +

    ", intValue2 = " + intValue2);

    // swap the two float variables// (uses the Swap() method that accepts int parameters)mySwapper.Swap(ref intValue1, ref intValue2);

    // display the final valuesSystem.Console.WriteLine("final intValue1 = " + intValue1 +

    ", intValue2 = " + intValue2);

    // declare two float variablesfloat floatValue1 = 2f;float floatValue2 = 5f;System.Console.WriteLine("initial floatValue1 = " + floatValue1 +

    ", floatValue2 = " + floatValue2);

    // swap the two float variables// (uses the Swap() method that accepts float parameters)mySwapper.Swap(ref floatValue1, ref floatValue2);

    // display the final valuesSystem.Console.WriteLine("final floatValue1 = " + floatValue1 +

    ", floatValue2 = " + floatValue2);mySwapper.Swap(ref floatValue1, ref floatValue2);

    }

    }}

    24. // More operator overloading.using System;namespace test{

    // A three-dimensional coordinate class.classThreeD{

    int x, y, z; // 3-D coordinatespublic ThreeD() { x = y = z = 0; }public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }// Overload binary +.publicstaticThreeDoperator +(ThreeD op1, ThreeD op2){

    ThreeD result = newThreeD();/* This adds the coordinates of two points and returns the result. */result.x = op1.x + op2.x;result.y = op1.y + op2.y;result.z = op1.z + op2.z;return result;

    }// Overload binary -.publicstaticThreeDoperator -(ThreeD op1, ThreeD op2){

    ThreeD result = newThreeD();/* Notice the order of the operands. op1 is the left

    operand and op2 is the right. */result.x = op1.x - op2.x;result.y = op1.y - op2.y;result.z = op1.z - op2.z;

    return result;}// Overload unary -.publicstaticThreeDoperator -(ThreeD op){

  • 8/3/2019 C# Walk Through - 1

    14/14

    Nucleusoftech Excellence In Microsoft .NET

    Nucleusoftech MS NET Walk Through 1 / Page 14 of 14

    ThreeD result = newThreeD();result.x = -op.x;result.y = -op.y;result.z = -op.z;return result;

    }// Overload unary ++.publicstaticThreeDoperator ++(ThreeD op){

    // for ++, modify argumentop.x++;op.y++;op.z++;return op;

    }// Show X, Y, Z coordinates.publicvoid show(){

    Console.WriteLine(x + ", " + y + ", " + z);}

    }publicclassThreeDDemo1{

    publicstaticvoid Main(){ThreeD a = newThreeD(1, 2, 3);ThreeD b = newThreeD(10, 10, 10);ThreeD c = newThreeD();Console.Write("Here is a: ");a.show();Console.WriteLine();Console.Write("Here is b: ");b.show();Console.WriteLine();c = a + b; // add a and b togetherConsole.Write("Result of a + b: ");c.show();Console.WriteLine();c = a + b + c; // add a, b and c togetherConsole.Write("Result of a + b + c: ");c.show();Console.WriteLine();c = c - a; // subtract aConsole.Write("Result of c - a: ");c.show();Console.WriteLine();c = c - b; // subtract bConsole.Write("Result of c - b: ");c.show();Console.WriteLine();c = -a; // assign -a to cConsole.Write("Result of -a: ");

    c.show();Console.WriteLine();a++; // increment aConsole.Write("Result of a++: ");a.show();

    }}

    }

    Happy C# Coding


Recommended