Probably a very simple question, and maybe I'm not even doing it right in the first place. Done some research and having trouble understanding the second part.
Let's say I have two methods in C#, and I want to send the value of that variable to another method. This is how I've accomplished it, sending variable1s value to method 2
public void methodOne(string variable1)
{
variable1 = "testing";
myClass p = new myClass();
p.methodTwo(variable1);
}
public void methodTwo(string variable1)
{
Console.Write(variable1);
}
So this sends the information in variable1 from methodOne to methodTwo.
But what if I wanted to modify the variable in methodTwo, and then send it back to methodOne? Would I just do the same exact thing in methodTwo and utilize this again?
myClass p = new myClass();
p.methodOne(variable1);
My issue is obviously if I utilize that code, I'd get stuck in an infinite loop of going back and forth unless I added a break condition. It makes me think maybe I'm not even correctly considering how to do this, and there's an easier way I'm missing.
What you want to do is pass the variable ByRef, using the ref keyword.
using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
}
private static void Method1()
{
int myVar = 5;
Console.WriteLine($"myVar in Method1: {myVar}"); // 5
Method2(ref myVar);
Console.WriteLine($"myVar in Method2: {myVar}"); // 10
}
private static void Method2(ref int AnotherVar)
{
AnotherVar = 10;
}
}
}
This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 9 years ago.
I'm relatively new in C#, & I'm wondering when to use Delegates appropriately.
they are widely used in events declaration, but when should I use them in my own code and why are they useful? why not to use something else?
I'm also wondering when I have to use delegates and I have no other alternative.
Thank you for the help!
EDIT: I think I've found a necessary use of Delegates here
A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp {
/// <summary>
/// A class to define a person
/// </summary>
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
//Our delegate
public delegate bool FilterDelegate(Person p);
static void Main(string[] args) {
//Create 4 Person objects
Person p1 = new Person() { Name = "John", Age = 41 };
Person p2 = new Person() { Name = "Jane", Age = 69 };
Person p3 = new Person() { Name = "Jake", Age = 12 };
Person p4 = new Person() { Name = "Jessie", Age = 25 };
//Create a list of Person objects and fill it
List<Person> people = new List<Person>() { p1, p2, p3, p4 };
//Invoke DisplayPeople using appropriate delegate
DisplayPeople("Children:", people, IsChild);
DisplayPeople("Adults:", people, IsAdult);
DisplayPeople("Seniors:", people, IsSenior);
Console.Read();
}
/// <summary>
/// A method to filter out the people you need
/// </summary>
/// <param name="people">A list of people</param>
/// <param name="filter">A filter</param>
/// <returns>A filtered list</returns>
static void DisplayPeople(string title, List<Person> people, FilterDelegate filter) {
Console.WriteLine(title);
foreach (Person p in people) {
if (filter(p)) {
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
}
}
Console.Write("\n\n");
}
//==========FILTERS===================
static bool IsChild(Person p) {
return p.Age < 18;
}
static bool IsAdult(Person p) {
return p.Age >= 18;
}
static bool IsSenior(Person p) {
return p.Age >= 65;
}
}
}
Output:
Children:
Jake, 12 years old
Adults:
John, 41 years old
Jane, 69 years old
Jessie, 25 years old
Seniors:
Jane, 69 years old
I agree with everything that is said already, just trying to put some other words on it.
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class, "Please feel free to assign any method that matches this signature to the delegate and it will be called each time my delegate is called".
Typical use is of course events. All the OnEventX delegate to the methods the user defines.
Delegates are useful to offer to the user of your objects some ability to customize their behavior.
Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.
Say you want to write a procedure to integrate some real-valued function f (x) over some interval [a, b]. Say we want to use the 3-Point Gaussian method to do this (any will do, of course).
Ideally we want some function that looks like:
// 'f' is the integrand we want to integrate over [a, b] with 'n' subintervals.
static double Gauss3(Integrand f, double a, double b, int n) {
double res = 0;
// compute result
// ...
return res;
}
So we can pass in any Integrand, f, and get its definite integral over the closed interval.
Just what type should Integrand be?
Without Delegates
Well, without delegates, we'd need some sort of interface with a single method, say eval declared as follows:
// Interface describing real-valued functions of one variable.
interface Integrand {
double eval(double x);
}
Then we'd need to create a whole bunch of classes implementing this interface, as follows:
// Some function
class MyFunc1 : Integrand {
public double eval(double x) {
return /* some_result */ ;
}
}
// Some other function
class MyFunc2 : Integrand {
public double eval(double x) {
return /* some_result */ ;
}
}
// etc
Then to use them in our Gauss3 method, we need to invoke it as follows:
double res1 = Gauss3(new MyFunc1(), -1, 1, 16);
double res2 = Gauss3(new MyFunc2(), 0, Math.PI, 16);
And Gauss3 needs to do the look like the following:
static double Gauss3(Integrand f, double a, double b, int n) {
// Use the integrand passed in:
f.eval(x);
}
So we need to do all that just to use our arbitrary functions in Guass3.
With Delegates
public delegate double Integrand(double x);
Now we can define some static (or not) functions adhering to that prototype:
class Program {
public delegate double Integrand(double x);
// Define implementations to above delegate
// with similar input and output types
static double MyFunc1(double x) { /* ... */ }
static double MyFunc2(double x) { /* ... */ }
// ... etc ...
public static double Gauss3(Integrand f, ...) {
// Now just call the function naturally, no f.eval() stuff.
double a = f(x);
// ...
}
// Let's use it
static void Main() {
// Just pass the function in naturally (well, its reference).
double res = Gauss3(MyFunc1, a, b, n);
double res = Gauss3(MyFunc2, a, b, n);
}
}
No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.
Of course, delegates are more than just function pointers under the hood, but that's a separate issue (function chaining and events).
Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.
Pseudo:
function Retry(Delegate func, int numberOfTimes)
try
{
func.Invoke();
}
catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }
Or when you want to do late evaluation of code blocks, like a function where you have some Transform action, and want to have a BeforeTransform and an AfterTransform action that you can evaluate within your Transform function, without having to know whether the BeginTransform is filled, or what it has to transform.
And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.
Delegates Overview
Delegates have the following properties:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.
Let's assume an application downloads an XML, and then saves the XML to a database.
I have 2 projects here which build my solution: FTP and a SaveDatabase.
So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.
Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.
During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.
See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.
class FTP
{
public void Begin()
{
string filePath = DownloadFileFromFtpAndReturnPathName();
SaveDatabase sd = new SaveDatabase();
sd.Begin(filePath, NotifyFtpComplete());
}
private void NotifyFtpComplete()
{
//Code to send file to FTP site
}
}
class SaveDatabase
{
private void Begin(string filePath, delegateType NotifyJobComplete())
{
SaveToTheDatabase(filePath);
/* InvokeTheDelegate -
* here we can execute the NotifyJobComplete
* method at our preferred moment in the application,
* despite the method being private and belonging
* to a different class.
*/
NotifyJobComplete.Invoke();
}
}
So, with that explained, we can do it for real now with this Console Application using C#
using System;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that
* the SaveToDatabase cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
//Note, this NotifyDelegate type is defined in the SaveToDatabase project
NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);
SaveToDatabase sd = new SaveToDatabase();
sd.Start(nofityDelegate);
Console.ReadKey();
}
/* this is the method which will be delegated -
* the only thing it has in common with the NofityDelegate
* is that it takes 0 parameters and that it returns void.
* However, it is these 2 which are essential.
* It is really important to notice that it writes
* a variable which, due to no constructor,
* has not yet been called (so _notice is not initialized yet).
*/
private static void NotifyIfComplete()
{
Console.WriteLine(_notice);
}
private static string _notice = "Notified";
}
public class SaveToDatabase
{
public void Start(NotifyDelegate nd)
{
/* I shouldn't write to the console from here,
* just for demonstration purposes
*/
Console.WriteLine("SaveToDatabase Complete");
Console.WriteLine(" ");
nd.Invoke();
}
}
public delegate void NotifyDelegate();
}
I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.
However, lastly, we can make it more useful by changing the delegate type to include a parameter.
using System.Text;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that the SaveToDatabase
* cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
SaveToDatabase sd = new SaveToDatabase();
/* Please note, that although NotifyIfComplete()
* takes a string parameter, we do not declare it,
* all we want to do is tell C# where the method is
* so it can be referenced later,
* we will pass the parameter later.
*/
var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);
sd.Start(notifyDelegateWithMessage );
Console.ReadKey();
}
private static void NotifyIfComplete(string message)
{
Console.WriteLine(message);
}
}
public class SaveToDatabase
{
public void Start(NotifyDelegateWithMessage nd)
{
/* To simulate a saving fail or success, I'm just going
* to check the current time (well, the seconds) and
* store the value as variable.
*/
string message = string.Empty;
if (DateTime.Now.Second > 30)
message = "Saved";
else
message = "Failed";
//It is at this point we pass the parameter to our method.
nd.Invoke(message);
}
}
public delegate void NotifyDelegateWithMessage(string message);
}
I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.
A delegate is a simple class that is used to point to methods with a specific signature, becoming essentially a type-safe function pointer. A delegate's purpose is to facilitate a call back to another method (or methods), after one has been completed, in a structured way.
While it could be possible to create an extensive set of code to perform this functionality, you don’t need too. You can use a delegate.
Creating a delegate is easy to do. Identify the class as a delegate with the "delegate" keyword. Then specify the signature of the type.
I need help with C# programming; I am new to it and I come from C background. I have a Console Application like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Add_Function
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
//why can't I not use it this way?
c = Add(a, b);
Console.WriteLine("a + b = {0}", c);
}//END Main
public int Add(int x, int y)
{
int result = x + y;
return result;
}//END Add
}//END Program
}//END Add_Function
It gives me this error on the line that I call Add():
An object reference is required for the non-static field, method, or property 'Add_Function.Program.Add(int, int)'
Can anyone please explain to me why I have this problem. Is this because the architecture of C# is different than C, and the way I call it is wrong? Thanks.
Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".
The other answers have already given you a quick way to fix your problem (just make Add a static function), but I'd like to explain why.
C# has a fundamentally different design paradigm than C. That paradigm is called object-oriented programming (OOP). Explaining all the differences between OOP and functional programming is beyond the scope of this question, but here's the short version as it applies to you.
Writing your program in C, you would have created a function that adds two numbers, and that function would exist independently and be callable from anywhere. In C# most functions don't exist independently; instead, they exist in the context of an object. In your example code, only an instance (an object) of the class Program knows how to perform Add. Said another way, you have to create an instance of Program, and then ask Program to perform an Add for you.
The solutions that people gave you, using the static keyword, route around that design. Using the static keyword is kind of like saying, "Hey, this function I'm defining doesn't need any context/state, it can just be called." Since your Add function is very simple, this makes sense. As you start diving deeper into OOP, you're going to find that your functions get more complicated and rely on knowing their state/context.
My advice: Pick up an OOP book and get ready to switch your brain from functional programming to OOP programming. You're in for a ride.
You should either make your Add function static like so:
static public int Add(int x, int y)
{
int result = x + y;
return result;
} //END Add
static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.
or you should create in instance of your Program class, and then call Add on this instance. Like so:
Program prog = new Program();
prog.Add(5,10);
This code gives you an error because your Add function needs to be static:
static public int Add(int x, int y)
In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.
Since public static void Main(string[] args) is static, all functions that it calls need to be static as well.
Because your function is an instance or non-static function you should create an object first.
Program p=new Program();
p.Add(1,1)
What that build error is telling you, that you have to either have an instance of Program or make Add static.
Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".
Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc...
this will work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
Func<int, int, int> funcAdd = (x, y) => x + y;
c=funcAdd.Invoke(a, b);
Console.WriteLine(Convert.ToString(c));
}
}
}
Just make your Add function static by adding the static keyword like this:
public static int Add(int x, int y)
you have to make you're function static like this
namespace Add_Function
{
class Program
{
public static void(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
//why can't I not use it this way?
c = Add(a, b);
Console.WriteLine("a + b = {0}", c);
}
public static int Add(int x, int y)
{
int result = x + y;
return result;
}
}
}
you can do Program.Add instead of Add
you also can make a new instance of Program by going like this
Program programinstance = new Program();
The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y); or you could just copy and paste your entire Add function above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
im kinda new to c#, so I came up with this problem. Question: why is func2 called?
oh, and one more thing. say I add a function to a delegate. In this function I call another delegate, however I want to make sure that every other function added to the first delegate is called before this function calls this delegate, is there any clean solution ( not really interested in getInvocationList).
Thanks guys, you're the best.
class Program
{
delegate void voidEvent();
voidEvent test;
private void func1()
{
Console.Write("func1");
test -= func2;
}
private void func2()
{
Console.WriteLine("func2");
}
static void Main(string[] args)
{
Program p = new Program();
p.test += p.func1;
p.test += p.func2;
p.test();
}
}
Every time you change a delegate (+= or -=), you're effectively creating an entire copy of the invocation list (the methods that will get called).
Because of that, when you call p.test();, you're going to invoke every delegate in the invocation list at that point in time. Changing this inside of one of those handlers will change it for the next call, but won't change the currently executing call.
Reed is of course correct. Here's another way to think about it.
class Number
{
public static Number test;
private int x;
public Number(int x) { this.x = x; }
public Number AddOne()
{
return new Number(x + 1);
}
public void DoIt()
{
Console.WriteLine(x);
test = test.AddOne();
Console.WriteLine(x);
}
public static void Main()
{
test = new Number(1);
test.DoIt();
}
}
Should that print 1, 1, or 1, 2? Why?
It should print 1, 1. When you say
test.DoIt();
that does not mean
Console.WriteLine(test.x);
test = test.AddOne();
Console.WriteLine(test.x);
! Rather, that means
Number temporary = test;
Console.WriteLine(temporary.x);
test = test.AddOne();
Console.WriteLine(temporary.x);
Changing the value of test does not change the value of this in DoIt.
You're doing exactly the same thing. Changing the value of test does not change the list of functions that you are invoking; you asked for a particular list of functions to be invoked and that list is going to be invoked. You don't get to change it halfway through, any more than you get to change the meaning of this halfway through a method call.
Hello I have the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myConsole
{
public delegate int showDelegate();
public class addmultipleClass
{
public int addNumbers(int a, int b)
{
return (a + b);
}
public int multiplyNumbers(int a, int b)
{
return (a * b);
}
}
class Delegate
{
static void Main(string[] args)
{
addmultipleClass myObj = new addmultipleClass();
showDelegate add = new showDelegate(myObj.addNumbers);
}
}
}
It is showing error like this No overload for 'addNumbers' matches delegate 'myConsole.showDelegate'
Why it is showing this error. Whats wrong in my code. Is it not correct way to reference the addNumbers() method.
Why should i use the delegate over here. I can achieve this by using class object. as myObj.addNumbers(10,20);
So what is the need for delegate?
Please help me.
Thank you all.
Modify showDelegate to match the parameters of addNumbers:
public delegate int showDelegate(int a, int b);
Delegates have to match the number and type of parameters in addition to your return type.
The second part of your question is essentially asking: "why delegates?". For that answer, I suggest you look at other Stack Overflow posts for much more detailed and precise answers, for a start:
Delegates, Why?
when & why to use delegates?
The purpose of delegates