Here is the direct text from working in Unity/C# book:
try creating a new method that takes in an int parameter and simply
prints it out to the console. No return type necessary. When you've
got that, call the method in Start, pass in a GenerateCharacter method
call as its argument, and take a look at the output.
I've tried a few different things (declaring variable in Start, creating new method and calling it, with Debug.Log in the body), but no luck. Not sure where to start.
public class LearningCurve : MonoBehaviour
{
void Start()
{
int characterLevel = 32;
int nextSkillLevel = GenerateCharacter("Spike", characterLevel);
Debug.Log(nextSkillLevel);
Debug.Log(GenerateCharacter("Faye", characterLevel));
}
public int GenerateCharacter(string name, int level)
{
//Debug.LogFormat("Character: {0} - Level: {1}", name, level);
return level + 5;
}
}
Start at the Action and Function types in C#
Action Delegate - Use it when you don't need any return type
Function Delegate - Use it when you need a return type
(Hint) You can do this:
int characterLevel = 1;
Func<string,int,int> functionStoringVariable = GenerateCharacter;
// Call the function by the variable
int result = functionStoringVariable("Spike", characterLevel);
Related
I have been trying for more time than i would like to admit to get this to work. I'm pretty new at programming so this might be a very simple question. (I thought that when i started at least)
I really need to know how i can increase an existing value in increments using a method.
class Program
{
static void Main(string[] args)
{
int TestValue = 0;
Console.WriteLine(TestValue);
TestingMethod(TestValue);
Console.WriteLine(TestValue);
TestingMethod(TestValue);
Console.WriteLine(TestValue);
}
static int TestingMethod(int Start)
{
Start++;
return Start;
}
}
I want the program to print out 1, 2 and 3 using some sort of method. (preferably basic since i want to understand what i'm actually doing.) I also want to use multiple values with this method so simply putting in numbers won't work for me here.
I've already tried the things i know but since i don't have much knowledge of programming i may have used them incorrectly so they don't really matter i think.
Your method is correct but you need to write:
Console.WriteLine(TestValue);
TestValue = TestingMethod(TestValue);
Console.WriteLine(TestValue);
TestValue = TestingMethod(TestValue);
Console.WriteLine(TestValue);
This works like using the string Replace method for example, where you need to assign to a string the result of the method, the same variable or another.
An alternative is to pass the parameter by reference, so it will be modified, else it is passed by value because int is a value type:
static void Main(string[] args)
{
int TestValue = 0;
Console.WriteLine(TestValue);
TestingMethod(ref TestValue);
Console.WriteLine(TestValue);
TestingMethod(ref TestValue);
Console.WriteLine(TestValue);
}
static void TestingMethod(ref int Start)
{
Start++;
}
Passing Reference-Type Parameters (C# Programming Guide)
Since “int Start” is not a reference, every time you call TestingMethod(TestValue) you are sending 0 to the method, you are also not doing anything to the return value, so the program always prints 0.
As the previous answer said, using ref at the signature is a good idea, another way of doing this could be by creating your own counter class that can be passed as a reference.
public class MethodCounter
{
private int counterValue = 0;
public MethodCounter(int initialCount = 0)
{
counterValue = initialCount;
}
public void IncreaseCount()
{
counterValue++;
}
public int GetCount()
{
return counterValue;
}
}
Making your program class look like this
class Program {
static void Main(string[] args) {
MethodCounter counter = new MethodCounter();
Console.WriteLine(counter.GetCount());
TestingMethod(counter);
Console.WriteLine(counter.GetCount());
TestingMethod(counter);
Console.WriteLine(counter.GetCount());
}
static void TestingMethod(MethodCounter counter)
{
counter.IncreaseCount();
}
}
When passing data into methods, there are two ways that it can happen
Pass-By-Reference
Pass-By-Value
Because int is a primivite data type, your data is being sent using pass-by-value by defualt. Here's a general reference for primitives https://en.wikipedia.org/wiki/Primitive_data_type
When passing primitive type variables to methods, they are generally sent using Pass-By-Value. This means that the method receives a copy of your variable - and not the actual variable itself. Since the operations performed are being done on a different copy of your variable, your original copy isnt acutally being changed.
When passing Non-Primitive variables to a method (like StringBuilder, or HttpClient), they are generally sent using Pass-By-Reference. This means that you are passing the reference to your variable, aka the location in memory where it is stored. when the method receives the reference, it can find the exact copy of the variable you were working with, and perform operations on it
As per your requirement, your code should look like this, you have not assigned the returned value to the TestValue.
public static void Main(string[] args)
{
int TestValue = 0;
TestValue = TestingMethod(TestValue);
Console.WriteLine(TestValue);
TestValue = TestingMethod(TestValue);
Console.WriteLine(TestValue);
TestValue = TestingMethod(TestValue);
Console.WriteLine(TestValue);
}
static int TestingMethod(int Start)
{
return Start+=1;
}
I try to set a method as a parameter but I can't do it.
I tried about ten solutions proposed on different topics but it didn't work that's why I create my own topic
public static void startThread(Method methodname (For exemple Class.test))
{
for (int i = 1; i <= Xenoris.threads; i++)
{
new Thread(new ThreadStart(methodname)).Start();
}
}
As you can see I try to do ThreadStart in a function but for that I need to have a method as a parameter which I can't do
To be more precise I want to make my own library and I need to be able to have methods as parameter like: Class.test
I hope someone can help me and I'm sorry for my bad English
In this case, ThreadStart itself is a delegate, so you could just use that as the parameter type:
public static void startThread(ThreadStart method)
{
for (int i = 1; i <= Xenoris.threads; i++)
{
new Thread(method).Start();
}
}
And you can directly pass in the name of the method without any parentheses:
startThread(SomeMethod);
Note that the method you pass must be a method that accepts no parameters and returns void.
I am trying to grasp the concept of delegate and I grabbed the following code from a SO post.
What I am not understanding is what is happening inside of Main method. I can tell from a surfacial look at it there is a new delegate object and methods with matching arguments and return types are being called by referencing the delegate object. I want to know what these three lines are doing specifically:
Valid v1 = new Valid(Test.checkInt);
v1 += new Valid(Test.checkMax);
v1 += new Valid(Test.checkMin);
Here is the actual code:
using System;
public delegate void Valid(int a);
public class Test {
public const int MAX_VALUE = 255;
public const int MIN_VALUE = 10;
public static void checkInt(int a) {
Console.Write("checkInt result of {0}: ", a);
if (a < MAX_VALUE && a > MIN_VALUE)
Console.WriteLine("max and min value is valid");
else
Console.WriteLine("max and min value is not valid");
}
public static void checkMax(int a) {
Console.Write("checkMax result of {0}: ", a);
if (a < MAX_VALUE)
Console.WriteLine("max value is valid");
else
Console.WriteLine("max value is not valid");
}
public static void checkMin(int a) {
Console.Write("checkMin result of {0}: ", a);
if (a > MIN_VALUE)
Console.WriteLine("min value is valid");
else
Console.WriteLine("min value is not valid");
Console.WriteLine("");
}
}
public class Driver {
public static void Main(string [] args) {
Valid v1 = new Valid(Test.checkInt);
v1 += new Valid(Test.checkMax);
v1 += new Valid(Test.checkMin);
v1(1);
v1(10);
v1(20);
v1(30);
v1(254);
v1(255);
v1(256);
Console.ReadLine();
}
}
Valid v1 = new Valid(Test.checkInt);
v1 += new Valid(Test.checkMax);
v1 += new Valid(Test.checkMin);
That code sets up a Multi-Cast Delegate. It means that, when you execute v1 with a parameter (which is what's happening in the Main method), it will pass that parameter to all three check methods and execute them in sequence. The method parameter is specified in the delegate declaration.
Valid v1 = new Valid(Test.checkInt);
v1 += new Valid(Test.checkMax);
v1 += new Valid(Test.checkMin);
The first line declares a new delegate v1 (analogous to a function pointer). For now, its pointing to Test.checkInt.
Then with the += operator you make the delegate point to a second method, promoting it to a MulticastDelegate. The same thing happens on the third line.
On the following lines you invoke the delegate, which in turn invokes all methods that it is pointing to. The parameters passed to the delegate, will be passed to each of these methods.
The three lines in question define delegates conforming to the signature of Valid, using methods with the corresponding return type and parameters. The += operator makes a so-called multicast delegate from regular delegates. When a multicast delegate is called, its implementation calls the component delegates, producing the effects that you see.
The += operator for delegates is a way to combine delegates. It will create a new delegate that, when called, will invoke all of the methods that the delegate would have invoked before, in addition to this new method.
In this case, after executing those lines of code, invoking v1 will execute Test.checkInt, Test.checkMax, and Test.checkMin.
What's a callback and how is it implemented in C#?
I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?
In computer programming, a callback is executable code that is passed as an argument to other code.
—Wikipedia: Callback (computer science)
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
A callback is a function that will be called when a process is done executing a specific task.
The usage of a callback is usually in asynchronous logic.
To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.
public delegate void WorkCompletedCallBack(string result);
public void DoWork(WorkCompletedCallBack callback)
{
callback("Hello world");
}
public void Test()
{
WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
DoWork(callback);
}
public void TestCallBack(string result)
{
Console.WriteLine(result);
}
In today C#, this could be done using lambda like:
public void DoWork(Action<string> callback)
{
callback("Hello world");
}
public void Test()
{
DoWork((result) => Console.WriteLine(result));
DoWork(Console.WriteLine); // This also works
}
Definition
A callback is executable code that
is passed as an argument to other code.
Implementation
// Parent can Read
public class Parent
{
public string Read(){ /*reads here*/ };
}
// Child need Info
public class Child
{
private string information;
// declare a Delegate
delegate string GetInfo();
// use an instance of the declared Delegate
public GetInfo GetMeInformation;
public void ObtainInfo()
{
// Child will use the Parent capabilities via the Delegate
information = GetMeInformation();
}
}
Usage
Parent Peter = new Parent();
Child Johny = new Child();
// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;
Johny.ObtainInfo(); // here Johny 'asks' Peter to read
Links
more details for C#.
A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.
Check out this link.
If you referring to ASP.Net callbacks:
In the default model for ASP.NET Web
pages, the user interacts with a page
and clicks a button or performs some
other action that results in a
postback. The page and its controls
are re-created, the page code runs on
the server, and a new version of the
page is rendered to the browser.
However, in some situations, it is
useful to run server code from the
client without performing a postback.
If the client script in the page is
maintaining some state information
(for example, local variable values),
posting the page and getting a new
copy of it destroys that state.
Additionally, page postbacks introduce
processing overhead that can decrease
performance and force the user to wait
for the page to be processed and
re-created.
To avoid losing client state and not
incur the processing overhead of a
server roundtrip, you can code an
ASP.NET Web page so that it can
perform client callbacks. In a client
callback, a client-script function
sends a request to an ASP.NET Web
page. The Web page runs a modified
version of its normal life cycle. The
page is initiated and its controls and
other members are created, and then a
specially marked method is invoked.
The method performs the processing
that you have coded and then returns a
value to the browser that can be read
by another client script function.
Throughout this process, the page is
live in the browser.
Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx
If you are referring to callbacks in code:
Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.
More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx
Dedication to LightStriker:
Sample Code:
class CallBackExample
{
public delegate void MyNumber();
public static void CallMeBack()
{
Console.WriteLine("He/She is calling you. Pick your phone!:)");
Console.Read();
}
public static void MetYourCrush(MyNumber number)
{
int j;
Console.WriteLine("is she/he interested 0/1?:");
var i = Console.ReadLine();
if (int.TryParse(i, out j))
{
var interested = (j == 0) ? false : true;
if (interested)//event
{
//call his/her number
number();
}
else
{
Console.WriteLine("Nothing happened! :(");
Console.Read();
}
}
}
static void Main(string[] args)
{
MyNumber number = Program.CallMeBack;
Console.WriteLine("You have just met your crush and given your number");
MetYourCrush(number);
Console.Read();
Console.Read();
}
}
Code Explanation:
I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.
Please let me know if you have any questions.
Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.
An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.
C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.
callback work steps:
1) we have to implement ICallbackEventHandler Interface
2) Register the client script :
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);
1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)
var finalfield= p1,p2,p3;
UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack
2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data
//do some server side operation and passed to "callbackResult"
3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side
callbackResult
4) Get the data at client side:
ReceiveServerData(text) , in text server response , we wil get.
A callback is a function passed as an argument to another function. This technique allows a function to invoke the parameter function argument and even to pass a value back to the caller. A callback function can be designed to run before/after the function has finished and can pass a value.
It is a kind of construct where you call a long running function and ask him to call you back once it has finished with can return a parameter result to the caller.
It's like someone calls you in the middle of your work asking for status and you say "you know what give me 5 min and i will call you back" and at the end you call him to update. If you are a function the caller just added and passed another function that you invoked at the end. This can simpley be written in C# as:
public void VinodSrivastav(Action statusUpdate){
//i am still here working..working
//i have finished, calling you
statusUpdate();
}
//invokes
stackoverflow.VinodSrivastav((cam) => {
Console.Write("Is it finished");
});
The one simple example is the iterator function where the return will be multiple times, one can argue that we have yield for it:
public void IntreationLoop(int min, int max,Action<int> Callback)
{
for(int i = min;i<= max;i++)
Callback(i);
}
//call
IntreationLoop(5,50,(x) => { Console.Write(x); }); //will print 5-50 numbers
In the code above the function return type is void but it has an Action<int> callback which is called and sends each item from the loop to the caller.
The same thing can be done with if..else or try..catch block as:
public void TryCatch(Action tryFor,Action catchIt)
{
try{
tryFor();
}
catch(Exception ex)
{
Console.WriteLine($"[{ex.HResult}] {ex.Message}");
catchIt();
}
}
And call it as:
TryCatch(()=>{
int r = 44;
Console.WriteLine("Throwing Exception");
throw new Exception("something is wrong here");
}, ()=>{
Console.WriteLine("It was a mistake, will not try again");
});
In 2022 we have Func & Action doing the same, please see the demo code below which shows how this can be be used:
void Main()
{
var demo = new CallbackDemo();
demo.DoWork(()=> { Console.WriteLine("I have finished the work"); });
demo.DoWork((r)=> { Console.WriteLine($"I have finished the work here is the result {r}"); });
demo.DoWork(()=> { Console.WriteLine($"This is passed with func"); return 5;});
demo.DoWork((f)=> { Console.WriteLine($"This is passed with func and result is {f}"); return 10;});
}
// Define other methods and classes here
public class CallbackDemo
{
public void DoWork(Action actionNoParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionNoParameter(); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Action<int> actionWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int> funcWithReturn)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
int c = funcWithReturn(); //execute
result += c;
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int,int> funcWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
result += funcWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
}
//powershell code
$quiotent = divRemainderQuiotent ($a) ($b) ([ref] $remainder) # I need to pass this $remainder as reference
For that I need to pass it as PSReference
//csharp code
private PSReference remainder= null;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly"),
Parameter(
Position = 2,
Mandatory = true,
ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
public PSReference Remainder // if I don’t use this and use a value type and later change it to ref (inside C#) the result won’t bubble up, which I think is bad.
{
set { remainder = value; }
}
But now the problem becomes, the function that takes this parameter as ref integer.
protected override void ProcessRecord()
{
//main method, this is executed when cmdlet is run
int r = remainder ; //this is the problem I cannot convert PSReference to other object type (integer here).
int q = _csharpDivideRemainderQuiotent(a,b, ref r); // if I change this function to take PSReference type, I will have to make changes down the line for every function.
WriteObject(q);
} // method ProcessRecord
I haven't used PSReference before but couldn't you just do this:
protected override void ProcessRecord()
{
//main method, this is executed when cmdlet is run
int r = Convert.ToInt32(this.Remainder.Value);
int q = _csharpDivideRemainderQuiotent(a,b, ref r);
this.Remainder.Value = r;
WriteObject(q);
}