Você está na página 1de 12

Basic Input & output with the Console Class: Many of the example applications make use of the

System.Console class. Console is one of many types defined in the System namespace. As its name implies, this class encapsulates input, output, and error stream manipulations. Thus, this type is mostly useful when creating console-based applications rather than Windows based or Web-based applications. Principal among the methods of System.Console are Read( ), ReadLine( ) Write( ) and WriteLine( ), all of which are defined as static. Prep By: Sunitha Pramod Page 8 WriteLine( ) pumps a text string (including a carriage return) to the output stream. The Write( ) method pumps text to the output stream without a carriage return. ReadLine( ) allows you to receive information from the input stream up until the carriage return, while Read( ) is used to capture a single character from the input stream. // Make use of the Console class to perform basic IO. using System; class helloclass { static int Main(string[] args) { Console.Write("\n\nEnter your name: "); string s = Console.ReadLine(); Console.WriteLine("Name is {0}\n", s); Console.Write("Enter your age: "); s = Console.ReadLine(); Console.WriteLine("you are {0} years old: ", s); Console.ReadLine(); return 0; } } Output: Enter your name: smith Name is smith Enter your age: 25 you are 25 years old: ``````````````````````````````````````````````````` 1. The Default Parameter Passing Behavior The default manner in which a parameter is sent into a function is by value. Simply put, if you do not mark an argument with a parameter-centric keyword, a copy of the data is passed into the function: using System; class Program { public static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes as you are modifying a copy // of the original data x = 1000; y = 2000;

return ans; } static void Main(string[] args) { int x=5,y=7; Console.WriteLine("Before call: X:{0},y:{1}",x,y); Console.WriteLine("Answer is: {0}",Add(x,y)); Console.WriteLine("After call: X: {0},y:{1}",x,y); Console.ReadLine(); } Prep By: Sunitha Pramod Page 20 } Output: Before call: X:5,y:7 Answer is: 12 After call: X: 5,y:7 2. The Reference (ref) parameters Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something by reference. using System; class Program { public static void swap(ref string st1,ref string st2) { string temp; temp = st1; st1 = st2; st2 = temp; } static void Main(string[] args) { string s1 = "First string"; string s2 = "second string"; Console.WriteLine("Before: {0},{1}", s1, s2); swap(ref s1, ref s2); Console.WriteLine("After: {0},{1}", s1, s2); Console.ReadLine(); } Output: Before: First string,second string After: second string,First string Here, the caller has assigned an initial value to local string data (s1 and s2). Once the call to swap returns, s1 now contains the values second string, while s2 contains the values First string. 3. The Output (out) parameters Prep By: Sunitha Pramod Page 21 Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation. Output parameters need the

out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as an output parameter. Output parameters are very similar to reference parameters. The only differences are: The variable specified on the invocation doesn't need to have been assigned a value before it is passed to the function member. If the function member completes normally, the variable is considered to be assigned afterwards (so you can then "read" it). The parameter is considered initially unassigned (in other words, you must assign it a value before you can "read" it in the function member). The parameter must be assigned a value before the function member completes normally. using System; class Program { public static void Add(int x, int y, out int ans) { ans = x + y; } static void Main(string[] args) { int ans; Add(90, 90, out ans); Console.WriteLine("90+90={0}", ans); Console.ReadLine(); } } OutPut: 90+90=180 //Returning multiple output parameters using System; class Program { public static void FillTheseValues(out int a, out string b, out bool c) { a=10; b="hello"; c = true; } static void Main(string[] args) { Prep By: Sunitha Pramod Page 22 int i; string str; bool b; FillTheseValues(out i, out str, out b); Console.WriteLine("int is: {0}", i); Console.WriteLine("String is: {0}", str); Console.WriteLine("Bool is :{0}", b); Console.ReadLine(); } } Output: int is: 10 String is: hello

Bool is :True 4. The Params Modifier: In C# 'params' parameter allows us to create a method that may be sent to a set of identically typed arguments as a single logical parameter. To better understand this situation let us see a program that calculates the average of any number of integers. using System; class Program { public static int Average(params int[] values) { int sum = 0; for (int i = 0; i < values.Length; i++) sum = sum + values[i]; return (sum / values.Length); } static void Main(string[] args) { //pass int values in comma separated form int average; average = Average(30, 40, 70); Console.WriteLine("The average is: {0}", average); Prep By: Sunitha Pramod Page 23 //Pass an array of int int[] data ={ 30, 40, 70 }; average=Average(data); Console.WriteLine("The avearge of the int array ele:{0}",average); Console.ReadLine(); } } Output: The average is: 46 The avearge of the int array ele:46 555555555555555 \Differences between value type and Reference type: Value types are stored in stack Reference types are stored in heap When we assign one value type to another value type, it is cloned and the two instances operate independently. For eg, a=b; A new memory ;location is allocated for a and it is hold the value individually. Changing the value of b does not affect a. When reference type is assigned to another reference type, the two reference share the same instance and change made by the one instance affects the other. For eg, a=b; a reference (pointer) is created for a and both a and b now points to same address. Any alteration made to b will affect a. Value types cannot be set to null Reference types can be set to null Converting value type to reference type is called boxing. Converting reference type to value type to called unboxing. Value types are by default passed by value to other methods.

Reference types are by default passed by reference to other methods. The stack holds value type variables plus return addresses for functions. All numeric types, ints, floats a ``````````````````````````````````````` Passing Reference Types by Value: using System; class person { public string fullName; public int age; public person() { } public person(string n, int a) { fullName = n; age = a; } public void printInfo() { Console.WriteLine("{0} is {1} years old", fullName, age); } } class program { public static void SendAPersonByValue(person p) { //change the age of p p.age = 99; Prep By: Sunitha Pramod Page 28 //will the caller see this reassignment p = new person("nikki", 25); } public static void Main(string[] args) { //passing reference types by value Console.WriteLine("******passing person object by value********"); person smith = new person("smith", 10); Console.WriteLine("Before by value call, person is:"); smith.printInfo(); SendAPersonByValue(smith); Console.WriteLine("After by value call, person is:"); smith.printInfo(); Console.ReadLine(); } } Output: ******passing person object by value******** Before by value call, person is: smith is 10 years old After by value call, person is: smith is 99 years old Passing Reference Types by Reference: using System;

class person { public string fullName; public int age; public person() { } public person(string n, int a) { fullName = n; age = a; } public void printInfo() { Console.WriteLine("{0} is {1} years old", fullName, age); } } Prep By: Sunitha Pramod Page 29 class program { public static void SendAPersonByReference(ref person p) { //change the age of p p.age = 99; //will the caller see this reassignment p = new person("nikki", 25); } public static void Main(string[] args) { //passing reference types by value Console.WriteLine("******passing person object by reference********"); person smith = new person("smith", 10); Console.WriteLine("Before by ref call, person is:"); smith.printInfo(); SendAPersonByReference(ref smith); Console.WriteLine("After by ref call, person is:"); smith.printInfo(); Console.ReadLine(); } } Output: ******passing person object by reference******** Before by ref call, person is: smith is 10 years old After by ref call, person is: nikki is 25 years old 77777777777777777 Understanding Boxing and Unboxing Operations: Boxing and unboxing is a essential concept in C# type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to

be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Prep By: Sunitha Pramod Page 30 Converting value type to reference type is called boxing by storing the variable in a System.Object. Converting reference type to value type to called unboxing The following example shows both boxing and unboxing: class Test { Public static void Main() { int i=1; object o = i; //boxing int j=(int) o; //unboxing } } An int value can be converted to object and back again to int When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just opposite. When an object box is cast back to its original value type, the value is coped out of the box and into the appropriate storage location. using System; class program { public static void Main(string[] args) { Int32 x1 = 10; object o1 = x1; // Implicit boxing Console.WriteLine("The Object o1 = {0}", o1); // prints out 10 //----------------------------------------------------------Int32 x2 = 10; object o2 = (object)x2; // Explicit Boxing Console.WriteLine("The object o2 = {0}", o2); // prints out 10 Console.ReadLine(); } } Output: Prep By: Sunitha Pramod Page 31 The Object o1 = 10 The object o2 = 10 Unboxing Custom Value Types: using System; struct Mypoint { public int x, y; } class program { //compiler error, since to access the field data of Mypoint, you must //first unbox the parameter. This is done in the following method. /*static void UseBoxedMypoint(object o)

{ Console.WriteLine({0},{1}},o.x,o.y); }*/ static void UseBoxedMypoint(object o) { if (o is Mypoint) { Mypoint p = (Mypoint)o; Console.WriteLine("{0},{1}", p.x, p.y); } else Console.WriteLine("You did not send a Mypoint"); } public static void Main(string[] args) { Mypoint p; p.x = 10; p.y = 20; UseBoxedMypoint(p); Console.ReadLine(); } } Output: 10,20 55555555555 Method Purpose public virtual bool Equals(object ob) whether the object is the same as the one referred to by ob. public static bool Equals(object ob1, whether ob1 is the same as ob2. Prep By: Sunitha Pramod Page 36 object ob2) protected Finalize() Performs shutdown actions prior to garbage collection. public virtual int GetHashCode() Returns the hash code. public Type GetType() Return the type of an object. protected object MemberwiseClone() Makes a "shallow copy" of the object. (The members are copied, but objects referred to by members are not.) public static bool ReferenceEquals(object ob1, object ob2) whether ob1 and ob2 refer to the same object. public virtual string ToString() Returns a string that describes the object. It is automatically called when an object is output using WriteLine().

6666666666666 .NET Array Types: In C#, an array index starts at zero. That means, first item of an array will be stored at 0th position. The position of the last item on an array will total number of items - 1. In C#, arrays can be declared as fixed length or dynamic. Fixed length array can stores a predefined number of items, while size of dynamic arrays increases as you add new items to the array. You can declare an array of fixed length or dynamic. For example, the following like declares a dynamic array of integers. int [] intArray; The following code declares an array, which can store 5 items starting from index 0 to 4. int [] intArray; intArray = new int[5]; The following code declares an array that can store 100 items starting from index 0 to 99. int [] intArray; intArray = new int[100]; Arrays can be divided into four categories. These categories are single-dimensional arrays, multidimensional arrays or rectangular arrays, jagged arrays, and mixed arrays. In C#, arrays are objects. That means declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator Prep By: Sunitha Pramod Page 41 The following code declares and initializes an array of three items of integer type. int [] intArray; intArray = new int[3] {0, 1, 2}; The following code declares and initializes an array of 5 string items. string[] strArray = new string[5] {"Ronnie", "Jack", "Lori", "Max", "Tricky"}; You can even direct assign these values without using the new operator. string[] strArray = {"Ronnie", "Jack", "Lori", "Max", "Tricky"}; You can initialize a dynamic length array as following string[] strArray = new string[] {"Ronnie", "Jack", "Lori", "Max", "Tricky"}; Arrays As Parameters (and Return Values): Once you created an array, you are free to pass it as a parameter and receive it as a member return vales. Example: using System; class program { static void PrintArrays(int[] MyInt) { Console.WriteLine("The int array is"); for (int i = 0; i < MyInt.Length; i++) Console.WriteLine(MyInt[i]); } static string[] GetStringArray() { string[] TheStrings = { "Hello", "What", "That", "stringarray" }; return TheStrings;//return a string array } public static void Main(string[] args) { int[] ages ={ 10, 20, 30, 40 };

PrintArrays(ages); //passing an array as parameter string[] strs = GetStringArray(); //Receiving a string array in a var strs Console.WriteLine("The string array is"); foreach (string s in strs) Console.WriteLine(s); Console.ReadLine(); Prep By: Sunitha Pramod Page 42 } } Output: The int array is 10 20 30 40 The string array is Hello What That stringarray Working with Multidimensional Arrays: using System; class program { public static void Main(string[] args) { //A rectangular MD array int[,] a; a = new int[3, 3]; //populate (3*3) array. for (int i = 0; i <3 ; i++) for (int j = 0; j <3; j++) a[i, j] = i * j; //print (3*3) array for (int i = 0; i <3; i++) { for (int j = 0; j <3; j++) { Console.Write(a[i, j] + "\t"); } Console.WriteLine(); } Console.ReadLine(); } Prep By: Sunitha Pramod Page 43 } 000 012 024 The System.Array Base Class: The Array class, defined in the System namespace, is the base class for arrays in C#.

Array class is an abstract base class but it provides CreateInstance method to construct an array. The Array class provides methods for creating, manipulating, searching, and sorting arrays. Table 1 describes Array class properties. IsFixedSize Return a value indicating if an array has a fixed size or not. IsReadOnly Returns a value indicating if an array is read-only or not. Length Returns the total number of items in all the dimensions of an array. Rank Returns the number of dimensions of an array. Table 1: The System.Array Class Properties Table 2 describes some of the Array class methods. BinarySearch This method searches a one-dimensional sorted Array for a value, using a binary search algorithm. Clear This method removes all items of an array and sets a range of items in the array to 0. Copy This method copies a section of one Array to another Array and performs type casting and boxing as required. CopyTo This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. CreateInstance This method initializes a new instance of the Array class. GetLength This method returns the number of items in an Array. Reverse This method reverses the order of the items in a one-dimensional Array or in a portion of the Array. Prep By: Sunitha Pramod Page 44 Sort This method sorts the items in one-dimensional Array objects. Write C# program to demonstrate the methods of Array class i,e copy, sort, reverse, and clear using System; class program { public static void Main(string[] args) { //Array of string string[] names = { "amir", "sharuk", "salman", "Hrithik" }; //print the names Console.WriteLine("\nNames are"); for(int i=0;i<names.Length;i++) Console.WriteLine("{0}",names[i]); //copy source array(names) to destination array(str) string[] str = new string[5]; Array.Copy(names, str, 4); Console.WriteLine("\nAfter copy the new name array is"); for (int i = 0; i < str.Length; i++) Console.WriteLine("{0}", str[i]); //print the sorted array Array.Sort(names); Console.WriteLine("\nAfter sorting array is"); for (int i = 0; i < names.Length; i++) Console.WriteLine("{0}", names[i]); //Reverse name array and print it Array.Reverse(names); Console.WriteLine("\nThe reverse array "); for(int i=0;i<names.Length;i++)

Console.WriteLine("{0}",names[i]); //clear out all except hrithik Array.Clear(names,1,3); Console.WriteLine("\nclear out all except hrithik"); for(int i=0;i<names.Length;i++) Console.WriteLine("{0}",names[i]); System.Console.ReadLine(); } } Output: Names are amir sharuk salman Hrithik After copy the new name array is amir sharuk salman Hrithik After sorting array is amir Hrithik salman sharuk The reverse array sharuk salman Hrithik amir clear out all except hrithik sharuk

Você também pode gostar