C# – Polymorphism

C# – Polymorphism ”; Previous Next The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as ”one interface, multiple functions”. Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time. Static Polymorphism The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are − Function overloading Operator overloading We discuss operator overloading in next chapter. Function Overloading You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. The following example shows using function print() to print different data types − Live Demo using System; namespace PolymorphismApplication { class Printdata { void print(int i) { Console.WriteLine(“Printing int: {0}”, i ); } void print(double f) { Console.WriteLine(“Printing float: {0}” , f); } void print(string s) { Console.WriteLine(“Printing string: {0}”, s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p.print(5); // Call print to print float p.print(500.263); // Call print to print string p.print(“Hello C++”); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Printing int: 5 Printing float: 500.263 Printing string: Hello C++ Dynamic Polymorphism C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Here are the rules about abstract classes − You cannot create an instance of an abstract class You cannot declare an abstract method outside an abstract class When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed. The following program demonstrates an abstract class − Live Demo using System; namespace PolymorphismApplication { abstract class Shape { public abstract int area(); } class Rectangle: Shape { private int length; private int width; public Rectangle( int a = 0, int b = 0) { length = a; width = b; } public override int area () { Console.WriteLine(“Rectangle class area :”); return (width * length); } } class RectangleTester { static void Main(string[] args) { Rectangle r = new Rectangle(10, 7); double a = r.area(); Console.WriteLine(“Area: {0}”,a); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Rectangle class area : Area: 70 When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. Dynamic polymorphism is implemented by abstract classes and virtual functions. The following program demonstrates this − Live Demo using System; namespace PolymorphismApplication { class Shape { protected int width, height; public Shape( int a = 0, int b = 0) { width = a; height = b; } public virtual int area() { Console.WriteLine(“Parent class area :”); return 0; } } class Rectangle: Shape { public Rectangle( int a = 0, int b = 0): base(a, b) { } public override int area () { Console.WriteLine(“Rectangle class area :”); return (width * height); } } class Triangle: Shape { public Triangle(int a = 0, int b = 0): base(a, b) { } public override int area() { Console.WriteLine(“Triangle class area :”); return (width * height / 2); } } class Caller { public void CallArea(Shape sh) { int a; a = sh.area(); Console.WriteLine(“Area: {0}”, a); } } class Tester { static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Rectangle class area: Area: 70 Triangle class area: Area: 25 Print Page Previous Next Advertisements ”;

C# – Properties

C# – Properties ”; Previous Next Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values. For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields. Accessors The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. For example − // Declare a Code property of type string: public string Code { get { return code; } set { code = value; } } // Declare a Name property of type string: public string Name { get { return name; } set { name = value; } } // Declare a Age property of type int: public int Age { get { return age; } set { age = value; } } Example The following example demonstrates use of properties − Live Demo using System; namespace tutorialspoint { class Student { private string code = “N.A”; private string name = “not known”; private int age = 0; // Declare a Code property of type string: public string Code { get { return code; } set { code = value; } } // Declare a Name property of type string: public string Name { get { return name; } set { name = value; } } // Declare a Age property of type int: public int Age { get { return age; } set { age = value; } } public override string ToString() { return “Code = ” + Code +”, Name = ” + Name + “, Age = ” + Age; } } class ExampleDemo { public static void Main() { // Create a new Student object: Student s = new Student(); // Setting code, name and the age of the student s.Code = “001”; s.Name = “Zara”; s.Age = 9; Console.WriteLine(“Student Info: {0}”, s); //let us increase age s.Age += 1; Console.WriteLine(“Student Info: {0}”, s); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Student Info: Code = 001, Name = Zara, Age = 9 Student Info: Code = 001, Name = Zara, Age = 10 Abstract Properties An abstract class may have an abstract property, which should be implemented in the derived class. The following program illustrates this − Live Demo using System; namespace tutorialspoint { public abstract class Person { public abstract string Name { get; set; } public abstract int Age { get; set; } } class Student : Person { private string code = “N.A”; private string name = “N.A”; private int age = 0; // Declare a Code property of type string: public string Code { get { return code; } set { code = value; } } // Declare a Name property of type string: public override string Name { get { return name; } set { name = value; } } // Declare a Age property of type int: public override int Age { get { return age; } set { age = value; } } public override string ToString() { return “Code = ” + Code +”, Name = ” + Name + “, Age = ” + Age; } } class ExampleDemo { public static void Main() { // Create a new Student object: Student s = new Student(); // Setting code, name and the age of the student s.Code = “001”; s.Name = “Zara”; s.Age = 9; Console.WriteLine(“Student Info:- {0}”, s); //let us increase age s.Age += 1; Console.WriteLine(“Student Info:- {0}”, s); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Student Info: Code = 001, Name = Zara, Age = 9 Student Info: Code = 001, Name = Zara, Age = 10 Print Page Previous Next Advertisements ”;

C# – Inheritance

C# – Inheritance ”; Previous Next One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on. Base and Derived Classes A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces. The syntax used in C# for creating derived classes is as follows − <acess-specifier> class <base_class> { … } class <derived_class> : <base_class> { … } Consider a base class Shape and its derived class Rectangle − Live Demo using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. Console.WriteLine(“Total area: {0}”, Rect.getArea()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Total area: 35 Initializing Base Class The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list. The following program demonstrates this − Live Demo using System; namespace RectangleApplication { class Rectangle { //member variables protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine(“Length: {0}”, length); Console.WriteLine(“Width: {0}”, width); Console.WriteLine(“Area: {0}”, GetArea()); } }//end class Rectangle class Tabletop : Rectangle { private double cost; public Tabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine(“Cost: {0}”, GetCost()); } } class ExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(4.5, 7.5); t.Display(); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Length: 4.5 Width: 7.5 Area: 33.75 Cost: 2362.5 Multiple Inheritance in C# C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this − Live Demo using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Base class PaintCost public interface PaintCost { int getCost(int area); } // Derived class class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. Console.WriteLine(“Total area: {0}”, Rect.getArea()); Console.WriteLine(“Total paint cost: ${0}” , Rect.getCost(area)); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Total area: 35 Total paint cost: $2450 Print Page Previous Next Advertisements ”;

C# – Anonymous Methods

C# – Anonymous Methods ”; Previous Next We discussed that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object. Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body. Writing an Anonymous Method Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example, delegate void NumberChanger(int n); … NumberChanger nc = delegate(int x) { Console.WriteLine(“Anonymous Method: {0}”, x); }; The code block Console.WriteLine(“Anonymous Method: {0}”, x); is the body of the anonymous method. The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object. For example, nc(10); Example The following example demonstrates the concept − Live Demo using System; delegate void NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static void AddNum(int p) { num += p; Console.WriteLine(“Named Method: {0}”, num); } public static void MultNum(int q) { num *= q; Console.WriteLine(“Named Method: {0}”, num); } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances using anonymous method NumberChanger nc = delegate(int x) { Console.WriteLine(“Anonymous Method: {0}”, x); }; //calling the delegate using the anonymous method nc(10); //instantiating the delegate using the named methods nc = new NumberChanger(AddNum); //calling the delegate using the named methods nc(5); //instantiating the delegate using another named methods nc = new NumberChanger(MultNum); //calling the delegate using the named methods nc(2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Anonymous Method: 10 Named Method: 15 Named Method: 30 Print Page Previous Next Advertisements ”;

C# – Generics

C# – Generics ”; Previous Next Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. A simple example would help understanding the concept − Live Demo using System; using System.Collections.Generic; namespace GenericApplication { public class MyGenericArray<T> { private T[] array; public MyGenericArray(int size) { array = new T[size + 1]; } public T getItem(int index) { return array[index]; } public void setItem(int index, T value) { array[index] = value; } } class Tester { static void Main(string[] args) { //declaring an int array MyGenericArray<int> intArray = new MyGenericArray<int>(5); //setting values for (int c = 0; c < 5; c++) { intArray.setItem(c, c*5); } //retrieving the values for (int c = 0; c < 5; c++) { Console.Write(intArray.getItem(c) + ” “); } Console.WriteLine(); //declaring a character array MyGenericArray<char> charArray = new MyGenericArray<char>(5); //setting values for (int c = 0; c < 5; c++) { charArray.setItem(c, (char)(c+97)); } //retrieving the values for (int c = 0; c< 5; c++) { Console.Write(charArray.getItem(c) + ” “); } Console.WriteLine(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − 0 5 10 15 20 a b c d e Features of Generics Generics is a technique that enriches your programs in the following ways − It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace. You can create your own generic interfaces, classes, methods, events, and delegates. You may create generic classes constrained to enable access to methods on particular data types. You may get information on the types used in a generic data type at run-time by means of reflection. Generic Methods In the previous example, we have used a generic class; we can declare a generic method with a type parameter. The following program illustrates the concept − Live Demo using System; using System.Collections.Generic; namespace GenericMethodAppl { class Program { static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } static void Main(string[] args) { int a, b; char c, d; a = 10; b = 20; c = ”I”; d = ”V”; //display values before swap: Console.WriteLine(“Int values before calling swap:”); Console.WriteLine(“a = {0}, b = {1}”, a, b); Console.WriteLine(“Char values before calling swap:”); Console.WriteLine(“c = {0}, d = {1}”, c, d); //call swap Swap<int>(ref a, ref b); Swap<char>(ref c, ref d); //display values after swap: Console.WriteLine(“Int values after calling swap:”); Console.WriteLine(“a = {0}, b = {1}”, a, b); Console.WriteLine(“Char values after calling swap:”); Console.WriteLine(“c = {0}, d = {1}”, c, d); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Int values before calling swap: a = 10, b = 20 Char values before calling swap: c = I, d = V Int values after calling swap: a = 20, b = 10 Char values after calling swap: c = V, d = I Generic Delegates You can define a generic delegate with type parameters. For example − delegate T NumberChanger<T>(T n); The following example shows use of this delegate − Live Demo using System; using System.Collections.Generic; delegate T NumberChanger<T>(T n); namespace GenericDelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger<int> nc1 = new NumberChanger<int>(AddNum); NumberChanger<int> nc2 = new NumberChanger<int>(MultNum); //calling the methods using the delegate objects nc1(25); Console.WriteLine(“Value of Num: {0}”, getNum()); nc2(5); Console.WriteLine(“Value of Num: {0}”, getNum()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Value of Num: 35 Value of Num: 175 Print Page Previous Next Advertisements ”;

C# – Exception Handling

C# – Exception Handling ”; Previous Next An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. Syntax Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following − try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed } You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Exception Classes in C# C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception. The following table provides some of the predefined exception classes derived from the Sytem.SystemException class − Sr.No. Exception Class & Description 1 System.IO.IOException Handles I/O errors. 2 System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. 3 System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type. 4 System.NullReferenceException Handles errors generated from referencing a null object. 5 System.DivideByZeroException Handles errors generated from dividing a dividend with zero. 6 System.InvalidCastException Handles errors generated during typecasting. 7 System.OutOfMemoryException Handles errors generated from insufficient free memory. 8 System.StackOverflowException Handles errors generated from stack overflow. Handling Exceptions C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the try, catch, and finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs − Live Demo using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine(“Exception caught: {0}”, e); } finally { Console.WriteLine(“Result: {0}”, result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Exception caught: System.DivideByZeroException: Attempted to divide by zero. at … Result: 0 Creating User-Defined Exceptions You can also define your own exception. User-defined exception classes are derived from the Exception class. The following example demonstrates this − Live Demo using System; namespace UserDefinedException { class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine(“TempIsZeroException: {0}”, e.Message); } Console.ReadKey(); } } } public class TempIsZeroException: Exception { public TempIsZeroException(string message): base(message) { } } public class Temperature { int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException(“Zero Temperature found”)); } else { Console.WriteLine(“Temperature: {0}”, temperature); } } } When the above code is compiled and executed, it produces the following result − TempIsZeroException: Zero Temperature found Throwing Objects You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as − Catch(Exception e) { … Throw e } Print Page Previous Next Advertisements ”;

C# – Interfaces

C# – Interfaces ”; Previous Next An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the ”what” part of the syntactical contract and the deriving classes define the ”how” part of the syntactical contract. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow. Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities. Declaring Interfaces Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration − public interface ITransactions { // interface members void showTransaction(); double getAmount(); } Example The following example demonstrates implementation of the above interface − Live Demo using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace InterfaceApplication { public interface ITransactions { // interface members void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = ” “; date = ” “; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine(“Transaction: {0}”, tCode); Console.WriteLine(“Date: {0}”, date); Console.WriteLine(“Amount: {0}”, getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction(“001”, “8/10/2012”, 78900.00); Transaction t2 = new Transaction(“002”, “9/10/2012″, 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Transaction: 001 Date: 8/10/2012 Amount: 78900 Transaction: 002 Date: 9/10/2012 Amount: 451900 Print Page Previous Next Advertisements ”;

C# – Indexers

C# – Indexers ”; Previous Next An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]). Syntax A one dimensional indexer has the following syntax − element-type this[int index] { // The get accessor. get { // return the value specified by index } // The set accessor. set { // set the value specified by index } } Use of Indexers Declaration of behavior of an indexer is to some extent similar to a property. similar to the properties, you use get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part. Defining a property involves providing a property name. Indexers are not defined with names, but with the this keyword, which refers to the object instance. The following example demonstrates the concept − Live Demo using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) namelist[i] = “N. A.”; } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = “”; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = “Zara”; names[1] = “Riz”; names[2] = “Nuha”; names[3] = “Asif”; names[4] = “Davinder”; names[5] = “Sunil”; names[6] = “Rubic”; for ( int i = 0; i < IndexedNames.size; i++ ) { Console.WriteLine(names[i]); } Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A. Overloaded Indexers Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string. The following example demonstrates overloaded indexers − Live Demo using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) { namelist[i] = “N. A.”; } } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = “”; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } public int this[string name] { get { int index = 0; while(index < size) { if (namelist[index] == name) { return index; } index++; } return index; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = “Zara”; names[1] = “Riz”; names[2] = “Nuha”; names[3] = “Asif”; names[4] = “Davinder”; names[5] = “Sunil”; names[6] = “Rubic”; //using the first indexer with int parameter for (int i = 0; i < IndexedNames.size; i++) { Console.WriteLine(names[i]); } //using the second indexer with the string parameter Console.WriteLine(names[“Nuha”]); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A. 2 Print Page Previous Next Advertisements ”;

C# – Methods

C# – Methods ”; Previous Next A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To use a method, you need to − Define the method Call the method Defining Methods in C# When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows − <Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body } Following are the various elements of a method − Access Specifier − This determines the visibility of a variable or a method from another class. Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method body − This contains the set of instructions needed to complete the required activity. Example Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class. class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } … } Calling Methods in C# You can call a method using the name of the method. The following example illustrates this − Live Demo using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine(“Max value is : {0}”, ret ); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Max value is : 200 You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test. Live Demo using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* local variable definition */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine(“Max value is : {0}”, ret ); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Max value is : 200 Recursive Method Call A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function − Live Demo using System; namespace CalculatorApplication { class NumberManipulator { public int factorial(int num) { /* local variable declaration */ int result; if (num == 1) { return 1; } else { result = factorial(num – 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //calling the factorial method {0}”, n.factorial(6)); Console.WriteLine(“Factorial of 7 is : {0}”, n.factorial(7)); Console.WriteLine(“Factorial of 8 is : {0}”, n.factorial(8)); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320 Passing Parameters to a Method When method with parameters is called, you need to pass the parameters to the method. There are three ways that parameters can be passed to a method − Sr.No. Mechanism & Description 1 Value parameters This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 2 Reference parameters This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. 3 Output parameters This method helps in returning more than one value. Print Page Previous Next Advertisements ”;

C# – Strings

C# – Strings ”; Previous Next In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class. Creating a String Object You can create string object using one of the following methods − By assigning a string literal to a String variable By using a String class constructor By using the string concatenation operator (+) By retrieving a property or calling a method that returns a string By calling a formatting method to convert a value or an object to its string representation The following example demonstrates this − using System; namespace StringApplication { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = “Rowan”; lname = “Atkinson”; char []letters= { ”H”, ”e”, ”l”, ”l”,”o” }; string [] sarray={ “Hello”, “From”, “Tutorials”, “Point” }; string fullname = fname + lname; Console.WriteLine(“Full Name: {0}”, fullname); //by using string constructor { ”H”, ”e”, ”l”, ”l”,”o” }; string greetings = new string(letters); Console.WriteLine(“Greetings: {0}”, greetings); //methods returning string { “Hello”, “From”, “Tutorials”, “Point” }; string message = String.Join(” “, sarray); Console.WriteLine(“Message: {0}”, message); //formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format(“Message sent at {0:t} on {0:D}”, waiting); Console.WriteLine(“Message: {0}”, chat); } } } When the above code is compiled and executed, it produces the following result − Full Name: RowanAtkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, October 10, 2012 Properties of the String Class The String class has the following two properties − Sr.No. Property & Description 1 Chars Gets the Char object at a specified position in the current String object. 2 Length Gets the number of characters in the current String object. Methods of the String Class The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods − Given below is the list of methods of the String class. Sr.No. Methods & Description 1 public static int Compare(string strA, string strB) Compares two specified string objects and returns an integer that indicates their relative position in the sort order. 2 public static int Compare(string strA, string strB, bool ignoreCase ) Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true. 3 public static string Concat(string str0, string str1) Concatenates two string objects. 4 public static string Concat(string str0, string str1, string str2) Concatenates three string objects. 5 public static string Concat(string str0, string str1, string str2, string str3) Concatenates four string objects. 6 public bool Contains(string value) Returns a value indicating whether the specified String object occurs within this string. 7 public static string Copy(string str) Creates a new String object with the same value as the specified string. 8 public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters. 9 public bool EndsWith(string value) Determines whether the end of the string object matches the specified string. 10 public bool Equals(string value) Determines whether the current String object and the specified String object have the same value. 11 public static bool Equals(string a, string b) Determines whether two specified String objects have the same value. 12 public static string Format(string format, Object arg0) Replaces one or more format items in a specified string with the string representation of a specified object. 13 public int IndexOf(char value) Returns the zero-based index of the first occurrence of the specified Unicode character in the current string. 14 public int IndexOf(string value) Returns the zero-based index of the first occurrence of the specified string in this instance. 15 public int IndexOf(char value, int startIndex) Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position. 16 public int IndexOf(string value, int startIndex) Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position. 17 public int IndexOfAny(char[] anyOf) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 18 public int IndexOfAny(char[] anyOf, int startIndex) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position. 19 public string Insert(int startIndex, string value) Returns a new string in which a specified string is inserted at a specified index position in the current string object. 20 public static bool IsNullOrEmpty(string value) Indicates whether the specified string is null or an Empty string. 21 public static string Join(string separator, params string[] value) Concatenates all the elements of a string array, using the specified separator between each element. 22 public static string Join(string separator, string[] value, int startIndex, int count) Concatenates the specified elements of a string array, using the specified separator between each element. 23 public int LastIndexOf(char value) Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object. 24 public int LastIndexOf(string value) Returns the zero-based index position of the last occurrence of a specified string within the current string object. 25 public string Remove(int startIndex) Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string. 26 public string Remove(int startIndex, int count) Removes the specified number of characters in the current string beginning at a specified position and returns the string. 27 public string Replace(char oldChar, char newChar) Replaces all occurrences of a specified Unicode character