C# – Delegates

C# – Delegates ”; Previous Next C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class. Declaring Delegates Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate. For example, consider a delegate − public delegate int MyDelegate (string s); The preceding delegate can be used to reference any method that has a single string parameter and returns an int type variable. Syntax for delegate declaration is − delegate <return type> <delegate-name> <parameter list> Instantiating Delegates Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method. For example − public delegate void printString(string s); … printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); Following example demonstrates declaration, instantiation, and use of a delegate that can be used to reference methods that take an integer parameter and returns an integer value. Live Demo using System; delegate int NumberChanger(int n); namespace DelegateAppl { 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 nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(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 Multicasting of a Delegate Delegate objects can be composed using the “+” operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The “-” operator can be used to remove a component delegate from a composed delegate. Using this property of delegates you can create an invocation list of methods that will be called when a delegate is invoked. This is called multicasting of a delegate. The following program demonstrates multicasting of a delegate − Live Demo using System; delegate int NumberChanger(int n); namespace DelegateAppl { 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 nc; NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); nc = nc1; nc += nc2; //calling multicast nc(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: 75 Using Delegates The following example demonstrates the use of delegate. The delegate printString can be used to reference method that takes a string as input and returns nothing. We use this delegate to call two methods, the first prints the string to the console, and the second one prints it to a file − Live Demo using System; using System.IO; namespace DelegateAppl { class PrintString { static FileStream fs; static StreamWriter sw; // delegate declaration public delegate void printString(string s); // this method prints to the console public static void WriteToScreen(string str) { Console.WriteLine(“The String is: {0}”, str); } //this method prints to a file public static void WriteToFile(string s) { fs = new FileStream(“c:\message.txt”, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.WriteLine(s); sw.Flush(); sw.Close(); fs.Close(); } // this method takes the delegate as parameter and uses it to // call the methods as required public static void sendString(printString ps) { ps(“Hello World”); } static void Main(string[] args) { printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); sendString(ps1); sendString(ps2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − The String is: Hello World Print Page Previous Next Advertisements ”;

C# – Discussion

Discuss C# ”; Previous Next C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its .NET initiative led by Anders Hejlsberg. This tutorial will teach you basic C# programming and will also take you through various advanced concepts related to C# programming language. Print Page Previous Next Advertisements ”;

C# – Operator Overloading

C# – Operator Overloading ”; Previous Next You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list. For example, go through the following function − public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object. Implementing the Operator Overloading The following program shows the complete implementation − Live Demo using System; namespace OperatorOvlApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public double getVolume() { return length * breadth * height; } public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } } class Tester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); // Declare Box2 of type Box Box Box3 = new Box(); // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine(“Volume of Box1 : {0}”, volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine(“Volume of Box2 : {0}”, volume); // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); Console.WriteLine(“Volume of Box3 : {0}”, volume); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 Overloadable and Non-Overloadable Operators The following table describes the overload ability of the operators in C# − Sr.No. Operators & Description 1 +, -, !, ~, ++, — These unary operators take one operand and can be overloaded. 2 +, -, *, /, % These binary operators take one operand and can be overloaded. 3 ==, !=, <, >, <=, >= The comparison operators can be overloaded. 4 &&, || The conditional logical operators cannot be overloaded directly. 5 +=, -=, *=, /=, %= The assignment operators cannot be overloaded. 6 =, ., ?:, ->, new, is, sizeof, typeof These operators cannot be overloaded. Example In the light of the above discussions, let us extend the preceding example, and overload few more operators − Live Demo using System; namespace OperatorOvlApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public double getVolume() { return length * breadth * height; } public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; } public static bool operator == (Box lhs, Box rhs) { bool status = false; if (lhs.length == rhs.length && lhs.height == rhs.height && lhs.breadth == rhs.breadth) { status = true; } return status; } public static bool operator !=(Box lhs, Box rhs) { bool status = false; if (lhs.length != rhs.length || lhs.height != rhs.height || lhs.breadth != rhs.breadth) { status = true; } return status; } public static bool operator <(Box lhs, Box rhs) { bool status = false; if (lhs.length < rhs.length && lhs.height < rhs.height && lhs.breadth < rhs.breadth) { status = true; } return status; } public static bool operator >(Box lhs, Box rhs) { bool status = false; if (lhs.length > rhs.length && lhs.height > rhs.height && lhs.breadth > rhs.breadth) { status = true; } return status; } public static bool operator <=(Box lhs, Box rhs) { bool status = false; if (lhs.length <= rhs.length && lhs.height <= rhs.height && lhs.breadth <= rhs.breadth) { status = true; } return status; } public static bool operator >=(Box lhs, Box rhs) { bool status = false; if (lhs.length >= rhs.length && lhs.height >= rhs.height && lhs.breadth >= rhs.breadth) { status = true; } return status; } public override string ToString() { return String.Format(“({0}, {1}, {2})”, length, breadth, height); } } class Tester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); // Declare Box2 of type Box Box Box3 = new Box(); // Declare Box3 of type Box Box Box4 = new Box(); double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); //displaying the Boxes using the overloaded ToString(): Console.WriteLine(“Box 1: {0}”, Box1.ToString()); Console.WriteLine(“Box 2: {0}”, Box2.ToString()); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine(“Volume of Box1 : {0}”, volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine(“Volume of Box2 : {0}”, volume); // Add two object as follows: Box3

C# – Events

C# – Events ”; Previous Next Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication. Using Delegates with Events The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber class. Events use the publisher-subscriber model. A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects. A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class. Declaring Events To declare an event inside a class, first of all, you must declare a delegate type for the even as: public delegate string BoilerLogHandler(string str); then, declare the event using the event keyword − event BoilerLogHandler BoilerEventLog; The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised. Example Live Demo using System; namespace SampleApp { public delegate string MyDel(string str); class EventProgram { event MyDel MyEvent; public EventProgram() { this.MyEvent += new MyDel(this.WelcomeUser); } public string WelcomeUser(string username) { return “Welcome ” + username; } static void Main(string[] args) { EventProgram obj1 = new EventProgram(); string result = obj1.MyEvent(“Tutorials Point”); Console.WriteLine(result); } } } When the above code is compiled and executed, it produces the following result − Welcome Tutorials Point Print Page Previous Next Advertisements ”;