How can I add a method as a parameter of a function - c#

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.

Related

Using a method call as an argument for an established method

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);

WPF Command Line Argument Routing

I have a WPF application that I'm starting to develop. I have a 40 or so methods that are accessible through the UI, but also need to be executed by passing parameters via the command line.
Currently i have the following, that allows me to catch the arguments on the App.xaml.cs...
public partial class App : Application
{
string[] args = MyApplication.GetCommandLineArgs();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
private void Application_Startup(object sender, StartupEventArgs e)
{
for (int index = 1; index < args.Length; index += 2)
{
dictionary.Add(args[index], args[index + 1]);
}
if (dictionary.Keys.Contains("/Task"))
{
MessageBox.Show("There is a Task");
}
}
}
}
I am looking to pass a argument at the start of every call through the command line. If i pass
/Task ThisIsTheTask
I can read this from the dictionary. And then execute the related method.
My question is what is the best way of "routing" the task parameter to a specific method. I will also be passing additional parameters after the task that will need to be passed to the method.
It could be considered an implementation of the service-locator anti-pattern, but one simple approach would be to have something like the following:
private readonly Dictionary<string, Action<string[]>> commands = new Dictionary<string, Action[]>
{
{"Task1", args => Task1Method(args[0], Int32.Parse(args[1]))}
}
private static Task1Method(string firstArgs, int secondArg)
{
}
Your code can then locate an Action<string[]> for the task specified on the command line, and pass the remaining parameters to the Action, e.g.
var commandLineArgs = Environment.GetCommandLineArgs();
var taskName = commandLineArgs[1];
// Locate the action to execute for the task
Action<string[]> action;
if(!commands.TryGetValue(taskName, out action))
{
throw new NotSupportedException("Task not found");
}
// Pass only the remaining arguments
var actionArgs = new string[commandLineArgs.Length-2];
commandLineArgs.CopyTo(actionArgs, 2);
// Actually invoke the handler
action(actionArgs);
If you are able to use third-party, open source libraries I would suggest taking a look at ManyConsole, it is available via NuGet here.
ManyConsole allows you to define ConsoleCommand implementations (see here for an example implementation), which can have many parameters. You are then able to use a ConsoleCommandDispatcher to route to the appropriate ConsoleCommand implementation based upon the command-line arguments (see here for an example).
I am in no way affiliated with ManyConsole, but I have used the library and found it to be very effective.
I'd suggest one (or more) properties on the application class of your program that expose them. Access during runtime can then be done by using something like
(Application.Current as App).MyTask
which can then be further wrapped for convenience.
Also, you can write your own "Main" method in WPF too - that way you would have easier access to the parameters array and could do processing before WPF starts up if you need to. I'll edit in how if you need that.

Dynamically invoking a Void Method with a String name in C#

my application is currently reading in a list of methods that I need to invoke, from the Database, and putting them into strings.
I want to be able to invoke these methods by their name, and pass parameters to them.
Heres a simple example of what I want to achieve:
protected void Page_Load(object sender, EventArgs e)
{
...
...
string MethodOne = "CombineText";
string WordOne = "Hello";
string WordTwo = "World";
CombineText(WordOne, WordTwo);
}
public void CombineText(string WordOne, string WordTwo)
{
Console.WriteLine(WordOne+" "+WordTwo);
}
I've seen plenty of examples online about invoking static methods, but I can't figure out how to invoke Public Void methods by name from strings.
Does anybody have any ideas? Much Appreciated!
You can use reflection.
MethodInfo mi = this.GetType().GetMethod(MethodOne);
mi.Invoke(this, new object[] { WordOne, WordTwo };
I would recommend using a switch instead of trying to call the method based on it's name.
switch(MethodOne)
{
case "CombineText":
CombineText(WordOne, WordTwo);
break;
default:
Console.WriteLine("Invalid function: " + MethodOne);
break;
}
This has the advantage of ensuring that you only accept valid arguments, and provides a way to sanitize the inputs on a per-function basis before evaluating (maybe you want to strip spaces from WordTwo for one function, for instance, or you want to pass the longer one in as the first parameter regardless of order.).
Assuming the method is an instance method of the current type:
MethodInfo method = this.GetType().GetMethod(MethodOne);
method.Invoke(this, new[] { WordOne, WordTwo });
You need to look at reflection. You need to do something like this:
Type type = GetType();
MethodInfo method = type.GetMethod(Method);
Method.Invoke(this, new object[] { WordOne, WordTwo });
http://msdn.microsoft.com/en-us/library/8zz808e6.aspx
http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx

what does callback mean? [duplicate]

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}]");
}
}

When create a static method

I use resharper and resharper adviced me to declare one method as static and the another not. But i can't understand why the other method can't be static ?
method recommended to be static
private static string Prehod(string retazec)
{
var pole = retazec.ToCharArray();
var output = "";
char? temp = null;
for (var i = 0; i < pole.Length; i++)
{
if (temp == null)
{
temp = pole[i];
continue;
}
output += pole[i].ToString() + temp.ToString();
temp = null;
}
return output;
}
and method not recommended to be static
public string HashToString(string hash,int dlzka)
{
var hashChar = hash.Substring(0, dlzka*2);
var retazec = "";
for (var i = 0; i < dlzka*2; i++)
{
if(i%2 != 0)
{
retazec += hashChar.Substring(i, 1);
}
}
return retazec;
}
Resharper doesn't give advices on public members of your classes, since they can be used by other classes.
But it's still a sign (not to say 'smell') for you if public instance methods don't need instance at all.
I can't see any reason why the second method can't be static, as to why Resharper suggests one and not the other... you'd have to ask the Resharper developers. Remember, it's a tool, not a rule book.
I don't see why your second method couldn't be static. As far as I can tell, it doesn't access any instance fields.
It wouldn't be a problem mnaking it static. So much to your question why it couldn't be static. As for ReSharper, I don't know why it doesn't recommend it as static whereas it does this for the other method.
Your first method is private, and probably used statically inside the class. Eg: var ehy = Prehod("testing");.
The second method is public. Probably you use it already somewhere like:
var okBaby = new MyClass();
Console.WriteLine(okBaby.HashToString("something", 10));
And resharper probably thinks there is a reason for it to be so, and doesn't suggest the change.
Just a blind shot, though.
Both methods can be static: they don't use any instance members of your class. And both methods can be instance methods. But a method being static or not should be implied by the possible uses of it, not by ReSharper. Do you expect your method to be called as part of an instance:
YourClass instance = new YourClass();
string x = instance.Prehod(...);
or do you expect your method to be called as part of the class:
string x = YourClass.Prehod(...);
It can be much later in the development process before you realize which is best. If you want to give users of your class the "feel" that it acts on the instance (new ClassName()), you must choose instance method. If you really need the method to be used without an instance (ClassName.YourMethod()) you must choose static.
UPDATE: it is uncommon to make a private method static, unless you need other static methods to call the private static methods. If only other instance methods use your private method, then there's no reason to make it a static method whatsoever.

Categories

Resources