Você está na página 1de 14

Nucleusoftech Excellence In Microsoft .

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

1.

2.

3.

4.

// Demonstrating Simple Program using System; namespace Test { class Program { static void Main(string[] args) { int myInteger; string myString; myInteger = 17; myString = "\"myInteger\" is"; Console.WriteLine("{0} {1}.", myString, myInteger); Console.ReadKey(); } } } // Demonstrating Type Conversions using System; namespace Test { class Program { static void 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(); } } } // Demonstrating Operations using System; namespace Test { class Program { static void Main(string[] args) { Console.WriteLine("Enter an integer:"); int myInt = Convert.ToInt32(Console.ReadLine()); bool isLessThan10 = myInt < 10; bool isBetween0And5 = (0 <= myInt) && (myInt <= 5); Console.WriteLine("Integer less than 10? {0}", isLessThan10); Console.WriteLine("Integer between 0 and 5? {0}", isBetween0And5); Console.WriteLine("Exactly one of the above is true? {0}", isLessThan10 ^ isBetween0And5); Console.ReadKey(); } } } // Demonstrating if else .

Nucleusoftech

MS.NET Walk Through 1 / Page 1 of 14

Nucleusoftech Excellence In Microsoft .NET


using System; namespace Test { class Program { static void 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"; else comparison = "greater than"; } Console.WriteLine("The first number is {0} the second number." , comparison); Console.ReadKey(); } } } // Demonstrating Switch. using System; namespace Test { class Program { static void Main(string[] args) { const string myName = "ram"; const string popularName = "amitabh"; const string 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(); } } } // Demonstrating Interest Calculation. using System; namespace Test { class Program { static void Main(string[] args) { double balance, interestRate, targetBalance;

5.

6.

Nucleusoftech

MS.NET Walk Through 1 / Page 2 of 14

Nucleusoftech Excellence In Microsoft .NET


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; using C = System.Console; namespace Test { class Program { static void Main(string[] args) { DateTime dateTime = DateTime.Now; // invoking Current System Date. C.WriteLine("d = {0:d}", dateTime); // mm/dd/yyyy C.WriteLine("D = {0:D}", dateTime); // month dd, yyyy C.WriteLine("f = {0:f}", dateTime); // day, month dd, yyyy hh:mm C.WriteLine("F = {0:F}", dateTime); // day,month dd,yyyy HH:mm:ss AM/PM C.WriteLine("g = {0:g}", dateTime); // mm/dd/yyyy HH:mm C.WriteLine("G = {0:G}", dateTime); // mm/dd/yyyy hh:mm:ss C.WriteLine("M = {0:M}", dateTime); // month dd C.WriteLine("R = {0:R}", dateTime); // ddd Month yyyy hh:mm:ss GMT C.WriteLine("s = {0:s}", dateTime); // yyyy-mm-dd hh:mm:ss (Sortable) C.WriteLine("t = {0:t}", dateTime); // hh:mm AM/PM C.WriteLine("T = {0:T}", dateTime); // hh:mm:ss AM/PM C.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/PM C.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); } } } // Demonstrating String Methods. using System; namespace Test { class Program { static void Main() { char[] characterArray; int position; string result, string1; string1 = "The education of Cissy!"; characterArray = new char[30]; // create the output string result = "string = \"" + string1 + "\"";

8.

Nucleusoftech

MS.NET Walk Through 1 / Page 3 of 14

Nucleusoftech Excellence In Microsoft .NET


// Length property result += "\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 position position = string1.IndexOf("Cissy"); result += "\n'Cissy' starts at index: "+ position; // change case of string result += "\nlower case string: \""+ string1.ToLower() + "\""; result += "\nupper case string: \""+ string1.ToUpper() + "\""; // indexing, loop through characters // in string1 and display in reverse order result += "\nreverse string: \""; for (int i = string1.Length - 1; i >= 0; i--) { result += string1[i]; } // Replace method result += "\"\nreplace 'educ' with 'matur': "; result += "\"" + string1.Replace("educ", "matur") + "\""; // Use the CopyTo method to copy characters // from string1 into characterArray string1.CopyTo(0, characterArray, 0, 6); result += "\nFirst 6 characters of array contain: \""; // display array for (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 { class Program { static void 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 <= noYears) // loop through number of years specified {

Nucleusoftech

MS.NET Walk Through 1 / Page 4 of 14

Nucleusoftech Excellence In Microsoft .NET


decimal interestPaid = principal * (interest / 100); // calculate interest principal += interestPaid; // calculate new principal principal = decimal.Round(principal, 2); // round to the nearest penny Console.WriteLine("Year " + year + " Rs. " + principal); year++; } Console.WriteLine("\nPress Enter to stop"); Console.ReadKey(); } } 10. } // Measuring Time of execution in a task Method 1 using System; namespace Test { class Program { static void Main() { DateTime startTime = DateTime.Now; Console.WriteLine("Started: {0}", startTime); // Execute the task to be timed for (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(); } } } // Measuring Time of execution in a task Method 2 using System; using System.Diagnostics; namespace Test { class Program { static void Main() { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 1; i < 1000000; i++) { } // Execute the task to be timed watch.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 elements using System; namespace Test { public class Program { static void Main(string[] args) { string[] strings = { "beta", "theta", "gamma", "alpha" }; Console.WriteLine("Array elements: "); DisplayArray(strings); Array.Sort(strings); DisplayArray(strings);

11.

Nucleusoftech

MS.NET Walk Through 1 / Page 5 of 14

Nucleusoftech Excellence In Microsoft .NET


} public static void DisplayArray(Array array) { foreach (object o in array) { Console.Write("{0} ", o); } Console.WriteLine(); } 13. } } // Reverse Array element order using System; namespace Test { public class Program { static void Main(string[] args) { string[] strings = { "alpha", "beta", "gamma" }; Console.WriteLine("Array elements: "); DisplayArray(strings); Array.Reverse(strings); DisplayArray(strings); } public static void DisplayArray(Array array) { foreach (object o in array) { Console.Write("{0} ", o); } Console.WriteLine(); } } } // demonstrating class access modifiers using System; namespace Test { class Car { // declare the fields public string make; protected internal string model; internal string color; protected int horsepower = 150; private int yearBuilt; // define the methods public void SetYearBuilt(int yearBuilt) { yearBuilt = yearBuilt; } public int GetYearBuilt() { return yearBuilt; } public void Start() { Console.WriteLine("Starting car ..."); TurnStarterMotor(); System.Console.WriteLine("Car started"); } private void TurnStarterMotor() { Console.WriteLine("Turning starter motor ..."); } } public class Example { public static void Main() {

14.

Nucleusoftech

MS.NET Walk Through 1 / Page 6 of 14

Nucleusoftech Excellence In Microsoft .NET


// create a Car object Car myCar = new Car(); // assign values to the Car object fields myCar.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 fields Console.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 field Console.WriteLine("myCar.GetYearBuilt() = " + myCar.GetYearBuilt()); myCar.Start();// call the Start() method // myCar.TurnStarterMotor(); // private method not accessible } } 15. } //Constructor, static constructor & destructor using System; namespace Test { class Test2 { static int 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"); } static void Main(string[] args) { Console.Out.WriteLine("Test2"); new Test2(); new Test2(); } } } //Calling non virtual using System; namespace Test { class Plane { public double TopSpeed() { return 300.0D; } } class Jet : Plane { public double TopSpeed() { return 900.0D; } } class Airport { static void Main(string[] args) {

16.

Nucleusoftech

MS.NET Walk Through 1 / Page 7 of 14

Nucleusoftech Excellence In Microsoft .NET


Plane plane = new Jet(); Console.WriteLine("planes top speed: {0}", plane.TopSpeed()); Console.ReadLine(); } } } The out put will be planes top speed: 300.0 This, will print "300" for the planes speed, since TopSpeed() is not virtual. To fix 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") //Calling virtual solution to program 15. using System; namespace Test { class Plane { public virtual double TopSpeed() { return 300.0D; } } class Jet : Plane { public override double TopSpeed() { return 900.0D; } } class Airport { static void Main(string[] args) { Plane plane = new Jet(); Console.WriteLine("planes top speed: {0}", plane.TopSpeed()); Console.ReadLine(); } } } The out put will be planes top speed: 900.0 using System; namespace Test { class Plane { public virtual double TopSpeed() { return 300.0D; } } class Jet : Plane { public override double TopSpeed() { return 900.0D; } } class Airport { static void Main(string[] args) { Plane plane = new Jet(); Console.WriteLine("plane's top speed: {0}", plane.TopSpeed()); Jet jet = new Jet(); Console.WriteLine("jet's top speed: {0}", jet.TopSpeed()); Console.ReadLine(); } } } The out put will be

17.

18.

Nucleusoftech

MS.NET Walk Through 1 / Page 8 of 14

Nucleusoftech Excellence In Microsoft .NET


19. planes top speed: 900.0 jet's top speed: 900.0 using System; namespace Test { class Plane { public virtual double TopSpeed() { return 300.0D; } } class Jet : Plane { public override double TopSpeed() { return 900.0D; } } class Airport { static void Main(string[] args) { Plane plane = new Plane(); Console.WriteLine("plane's top speed: {0}", plane.TopSpeed()); Jet jet = new Jet(); Console.WriteLine("jet's top speed: {0}", jet.TopSpeed()); Console.ReadLine(); } } } The out put will be planes top speed: 300.0 jet's top speed: 900.0 // Demostrates the use of an abstract class using System; namespace Test { public class MainClass { public static void Main(string[] strings) { SavingsAccount sa = new SavingsAccount(); sa.Withdrawal(100); CheckingAccount ca = new CheckingAccount(); ca.Withdrawal(100); } } abstract public class BankAccount { abstract public void Withdrawal(double dWithdrawal); } public class SavingsAccount : BankAccount { override public void Withdrawal(double dWithdrawal) { Console.WriteLine("Call to SavingsAccount.Withdrawal()"); } } public class CheckingAccount : BankAccount { override public void 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.

20.

Nucleusoftech

MS.NET Walk Through 1 / Page 9 of 14

Nucleusoftech Excellence In Microsoft .NET


using System; namespace nsAbstract { public class AbstractclsMain { static void Main(string[] args) { // Create an instance of the derived class. clsDerived derived = new clsDerived(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 class abstract class clsBase { // Declare an abstract method. Note the semicolon to end the declaration abstract public void Describe(); // Declare an abstract property that has only a get accessor. // Note that you // do not prove the braces for the accessor abstract public double DoubleProp { get; } // Declare an abstract property that has only a set accessor. abstract public int 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. abstract public string StringProp { get; set; } // Declare a method that will access the abstract members. public void 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 value StringProp = "StringProperty actually is stored in " + "the derived class."; // Now show StringProp Console.WriteLine(StringProp); // Finally, call the abstract method Describe(); } } // Derive a class from clsBase. You must implement the abstract members class clsDerived : clsBase { // Declare a constructor to set the DoubleProp member public 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. override public void Describe() { Console.WriteLine("You called Describe() from the base " + "class but the code body is in the \r\n" +

Nucleusoftech

MS.NET Walk Through 1 / Page 10 of 14

Nucleusoftech Excellence In Microsoft .NET


"derived class"); Console.WriteLine("m_Int = " + m_Int); } // Implement the DoubleProp property. This is where you provide a body // for the accessors. override public double DoubleProp { get { return (m_Double); } } // Implement the set accessor for IntProp. override public int IntProp { set { m_Int = value; } } // Implement StringProp, providing a body for both the get // and set accessors. override public string StringProp { get { return (m_String); } set { m_String = value; } } // Declare fields to support the properties. private double m_Double; private int m_Int; private string m_String; 22. } } // Demonstrating class example using inheritance using System; namespace test { class Vehicle { int pri_passengers; // number of passengers int pri_fuelcap; // fuel capacity in gallons int 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. public int range() { return mpg * fuelcap; } // Compute fuel needed for a given distance. public double fuelneeded(int miles) { return (double)miles / mpg; } // Properties public int passengers { get { return pri_passengers; } set { pri_passengers = value; } } public int fuelcap { get { return pri_fuelcap; } set { pri_fuelcap = value; } } public int mpg { get { return pri_mpg; } set { pri_mpg = value; }

Nucleusoftech

MS.NET Walk Through 1 / Page 11 of 14

Nucleusoftech Excellence In Microsoft .NET


} } // Use Vehicle to create a Truck specialization. class Truck : 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. public int cargocap { get { return pri_cargocap; } set { pri_cargocap = value; } } } public class TruckDemo { public static void Main() { // construct some trucks Truck semi = new Truck(2, 200, 7, 44000); Truck pickup = new Truck(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 overloading using System; namespace test { // declare the Swapper class class Swapper { // this Swap() method swaps two int parameters public void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; } // this Swap() method swaps two float parameters public void Swap(ref float x, ref float y) { float temp = x; x = y; y = temp; } } public class Program { public static void Main() {

Nucleusoftech

MS.NET Walk Through 1 / Page 12 of 14

Nucleusoftech Excellence In Microsoft .NET


// create a Swapper object Swapper mySwapper = new Swapper(); // declare two int variables int 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 values System.Console.WriteLine("final ", intValue2 = " + intValue2); intValue1 = " + intValue1 +

// declare two float variables float 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 values System.Console.WriteLine("final floatValue1 = " + floatValue1 + ", floatValue2 = " + floatValue2); mySwapper.Swap(ref floatValue1, ref floatValue2); } } } // More operator overloading. using System; namespace test { // A three-dimensional coordinate class. class ThreeD { int x, y, z; // 3-D coordinates public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } // Overload binary +. public static ThreeD operator +(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); /* 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 -. public static ThreeD operator -(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); /* 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 -. public static ThreeD operator -(ThreeD op) {

24.

Nucleusoftech

MS.NET Walk Through 1 / Page 13 of 14

Nucleusoftech Excellence In Microsoft .NET


ThreeD result = new ThreeD(); result.x = -op.x; result.y = -op.y; result.z = -op.z; return result; } // Overload unary ++. public static ThreeD operator ++(ThreeD op) { // for ++, modify argument op.x++; op.y++; op.z++; return op; } // Show X, Y, Z coordinates. public void show() { Console.WriteLine(x + ", " + y + ", " + z); } } public class ThreeDDemo1 { public static void Main() { ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); ThreeD c = new ThreeD(); 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 together Console.Write("Result of a + b: "); c.show(); Console.WriteLine(); c = a + b + c; // add a, b and c together Console.Write("Result of a + b + c: "); c.show(); Console.WriteLine(); c = c - a; // subtract a Console.Write("Result of c - a: "); c.show(); Console.WriteLine(); c = c - b; // subtract b Console.Write("Result of c - b: "); c.show(); Console.WriteLine(); c = -a; // assign -a to c Console.Write("Result of -a: "); c.show(); Console.WriteLine(); a++; // increment a Console.Write("Result of a++: "); a.show(); } } }

Happy C# Coding

Nucleusoftech

MS.NET Walk Through 1 / Page 14 of 14

Você também pode gostar