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
}
Related
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;
}
}
}
I am trying to build a dummy exercise for my own interest.
I have one form (form1) with two textboxes (textBox1, textBox2) and a button.
When I click the button, I want to add the numbers passed to the textboxes.
Now, I am trying to complicate things by introducing an Interface with the signatures of the appropriate methods to do the addition (ICalculate) and a class (Calculations) which implements the interface.
Then I have another class called Calc which gets initiated from Form1 by passing an ICalculate object and 2 integers (a,b) in its constructor.
Furthermore, the Calc class has a method (addition()) for adding the two integers, using the ICalculate object and the two integers instantiated at the constructor of the class and display the result on a messagebox.
The problem is that the compiler throws an error saying that the ICalculate object has not been initialized (Object reference not set to an instance of an object.)
The code is the following:
public interface ICalculate
{
int add(int x, int y);
int sub(int x, int y);
}
class Calculations : ICalculate
{
public int add(int a, int b)
{
return (a + b);
}
public int sub(int z, int k)
{
return (z - k);
}
}
class Calc
{
private ICalculate _nc;
private int _x, _y;
public Calc(ICalculate nc, int a, int b)
{
var _nc = nc;
_x = a;
_y = b;
}
public void addition()
{
MessageBox.Show(_nc.add(_x, _y).ToString());
}
}
}
The Form1 Code is the following:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var a = Int32.Parse(textBox1.Text);
var b = Int32.Parse(textBox2.Text);
var c = new Calc(new Calculations(), a, b);
c.addition();
}
}
Any help appreciated !
The problem is in the constructor of the Calc class.
Specifically, this row:
var _nc = nc;
You should remove the var:
_nc = nc;
What happens is that once you have the var keyword you are actually creating a local variable called _nc in the constructor, and assign the value of nc to it, so the class member called _nc is never initialized.
The compiler (tested on VS 2013) should issue a warning for this:
Field '<your namespace here>.Calc._nc' is never assigned to, and will always have its default value null
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.
I may have this wrong, but I've seen the way of creating an overloaded method that calls itself in the definition. It's something like:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a) : this (a, 10)
{ }
This is not the correct syntax, I know, but I can't find the correct syntax anywhere for some reason. What is the correct syntax for this?
You are confusing constructor syntax for method syntax. The only way to do that for a method is the obvious:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a)
{
myFunction(a, 10) ;
}
although as of C#4, you can use a optional parameters:
public void myFunction(int a, int b = 10)
{
//Some code here
}
What you wrote is close to right for constructors:
public class myClass
{
public myClass(int a, int b)
{
//Some code here
}
public myClass(int a) : this (a, 10)
{ }
}
Just do this:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a)
{
myFunction(a, 10)
}
You're confusing overloading with overriding. You can call a base constructor from an derived class like this:
public MyConstructor(int foo)
:base (10)
{}
public class BaseClass {
public virtual void SomeFunction(int a, int b) {}
}
public class Derived : BaseClass {
public override SomeFunction(int a, int b) {
base.SomeFunction(a, b * 10);
}
}