I am preparing for an exam and I have to examine various codes. One is about delegates in C# - I'm failing to see what it does, since I don't know if you can put functions from two different classes in one delegate.
Here's the code:
namespace konzolnaApplikacijaDelegateVoidMain {
public delegate int MyDelegate(int x);
class Program
{
public int number;
public Program (int x)
{
number = x;
}
public int Add(int x)
{
return x + 10;
}
public int Substract(int x)
{
return x - 10;
}
public int Multiply(int x)
{
return x * 2;
}
static void Main(string[] args)
{
MyDelegate delegate;
Program first = new Program(20);
Program second = new Program(50);
delegate = first.Add;
delegate += second.Add;
delegate -= first.Substract;
delegate += second.Multiply;
delegate += first.Add;
delegate(first.number);
delegate(second.number);
Console.Write("{0}", first.number + second.number);
}
}
}
Delegates are quite simple. Consider the following implementation of a delegate.
namespace DelegateExamples
{
class Program
{
//Declare a integer delegate to handle the functions in class A and B
public delegate int MathOps(int a, int b);
static void Main(string[] args)
{
MathOps multiply = ClassA.Multiply;
MathOps add = ClassB.Add;
int resultA = multiply(30, 30);
int resultB = add(1000, 500);
Console.WriteLine("Results: " + resultA + " " + resultB);
Console.ReadKey();
}
}
public class ClassA
{
public static int Multiply(int a, int b)
{
return a * b;
}
}
public class ClassB
{
public static int Add(int a, int b)
{
return a + b;
}
}
}
Related
No example from the official docs page.
public class MyClass
{
public static void Foo(params int[] args)
{
Bar(args) // error (I want to automatically pass args e.g.: Bar(args[0], args[1], args[2]...))
}
public static int Bar(int a, int b, int c, int d, int e) {
return a + b + c + d + e;
}
}
You can simply do like below
public static void Foo(params int[] args)
{
Bar(args); // error (I want to automatically pass args e.g.: Bar(args[0], args[1], args[2]...))
}
public static int Bar(params int [] values)
{
int total = 0;
foreach (int value in values)
{
total += value;
}
return total;
//return a + b + c + d + e;
}
using System;
using System.Linq;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo(1, 2, 3, 4, 5)); //outputs 15
}
public static int Foo(params int[] args)
{
return (int)typeof(Program).GetMethod(nameof(Bar), BindingFlags.Public | BindingFlags.Static).Invoke(null, args.Select(v => (object)v).ToArray());
}
public static int Bar(int a, int b, int c, int d, int e)
{
return a + b + c + d + e;
}
}
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();
}
}
in the above code function called and calling function are in same class.... can we use like both in seperate classes?
if its possible please give an example ......
Surely you can.
Just put your methods in a separate class and create an instance of it to access them:
class Arithmetic
{
int num = 10;
public int AddNum(int p)
{
num += p;
return num;
}
public int MultNum(int q)
{
num *= q;
return num;
}
}
Now call the methods:
class TestDelegate
{
public delegate int NumberChanger(int n);
static void Main(string[] args)
{
//create instance of class
Arithmetic art = new Arithmetic();
//create delegate instances
NumberChanger nc1 = new NumberChanger(art.AddNum); //call with reference
NumberChanger nc2 = new NumberChanger(art.MultNum); //call with reference
//calling the methods using the delegate objects
//add
Console.WriteLine("Value of Num: {0}", nc1(25)); //use it directly because your delegate returns a value
//product
Console.WriteLine("Value of Num: {0}", nc2(5)); //use it directly because your delegate returns a value
Console.ReadKey();
}
}
Note: You don't need getNum() method as you are already returning value from every method and your delegate returns it as well. Also I have removed static from everywhere because it seems you need it.
using System;
namespace _1._75_Using_a_delegate
{
public class Program
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y) { return x + y; }
public int Multiply(int x, int y) { return x * y; }
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
public static void Main()
{
//call and execute UseDelegate()
}
}
}
This should output the above results of 7 and 12.
The delegate function is not directly callable from main in the current state.
Why can't the delegate be seen from main?
Is it necessary to create a class?
How should the delegate function be called?
You cannot call the non-static method from static Method so you have to implement another class like
internal class Check
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
}
your call it from your Main Method like
private static void Main(string[] args)
{
new Check().UseDelegate();
}
You don't call the method at all, and you can't now since the Main method is static and your methods are not.
I would recommend to split your code off to a second class, which is easier to call. (Instead of making all methods static)
public class Assignment
{ /* all code except the Main method goes here */ }
Then, in your Main method, instantiate an instance of the Assignment class and call UseDelegate:
public static void Main()
{
Assignment a = new Assignment();
a.UseDelegate();
Console.ReadKey(); // to prevent the console from closing immediate
}
I am using a delegate type to call multiple functions from a single point. But when I do like that , I am getting the result somewhat wrong.
public delegate int MyDel(int a,int b);
public static int Add(int a, int b) { return a+b; }
public static int Sub(int a, int b) { return a-b; }
public static void Meth_del()
{
int x,y;
MyDel _delegate;
_delegate = Add;
_delegate += Sub;
Console.WriteLine( _delegate(5,4));
}
Here I should get result 9 and then 1 but only 1 is printed. How ?
This is called Closure. This happens because on the call it will execute both of the subscribed methods and you will be shown with end result.
To avoid such behavior you can unsubscribe (_delegate = null), override subscribers (=) or subscribe (+=) after first call is made.
public static void Meth_del()
{
int x,y;
MyDel _delegate;
_delegate = Add;
// Prints out 9.
Console.WriteLine( _delegate(5,4));
// Override subscribtion.
_delegate = Sub;
// Prints out 1.
Console.WriteLine( _delegate(5,4));
}
Also you can use += to add subscribers to the delegate (as you have written in your question).
Even if both methods are called only the the last method in the delegate will return the result.
Furthermore, you have only one call of Console.WriteLine(), a function cannot receive multiple return values.
To achieve what you want you might have to queue your results like this.
public static Queue<int> Results = new Queue<int>();
public static void Add(int a, int b) { Results.Enqueue(a + b); }
public static void Sub(int a, int b) { Results.Enqueue(a - b); }
public delegate void MyDel(int a, int b);
public static void Meth_del()
{
int x, y;
MyDel _delegate;
_delegate = Add;
_delegate += Sub;
_delegate(5, 4);
while (Results.Any())
Console.WriteLine(Results.Dequeue());
}
Your code does execute both methods but it only displays the return value of the last added method. If you change your methods like this:
public static int Add(int a, int b) {
Console.WriteLine(a+b);
return a+b;
}
public static int Sub(int a, int b) {
Console.WriteLine(a-b);
return a-b;
}
you will see that 9 as well as 1 are written in the console.
Yes its quite obvious that the last method in the delegate will returns the result.
public static void Meth_del()
{
int x,y;
MyDel _delegate;
_delegate = Add;
Console.WriteLine( _delegate(5,4));
_delegate += Sub;
Console.WriteLine( _delegate(5,4));
}
I am very beginner in c#. I created base class and derived class but i do not understand behavior of constructor in derived class it gives error "does not contain constructor that take 0 arguments" how to use it in derived class
class A
{
public int x, y, z;
public A(int i, int j)
{
x = i;
y = j;
}
public void add(int i,int j)
{
z=x + y;
Console.WriteLine(z);
}
}
class B : A
{
public B (int k, int l)
{
x=k;
y=l;
}
public void multi(int k,int l)
{
z = x * y;
Console.WriteLine(z);
}
}
Usage:
class Program
{
static void Main(string[] args)
{
A ad = new A(5,6);
B m = new B(8, 9);
}
}
Since B inherits A, it has to include a call to A's constructor, called the base contructor.
class B : A
{
public B (int k, int l)
: base(k, l)
{
}
}
This calls the code in A's constructor, populating x and y with the values in k and l.