This question already has answers here:
Pass Method as Parameter using C#
(13 answers)
Closed 3 years ago.
(I'm a bit new to programming so if this doesn't make sense just say so)
Let's say that a method takes in a void as parameter. Ex:
method(anotherMethod);
and I want to write the void inside of the brackets rather than writing the void and putting the name inside so rather than
void theVoid() {
doSomethingHere;
}
and then calling it like
method(theVoid());
I wanted to do
method({ doSomethingHere; })
directly, is it possible to do so?
The thing you are trying to do is called "lambda" it's anonymous functions
Here is the documentation for that.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
Your method will need to be passed a Delegate (if you do not return anything, an Action should be fine)
https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=netcore-2.2
Method(TheVoid()); // does not compile
Method(TheVoid); // compiles
using System;
public class Example
{
public void Method(Action func)
{
func();
}
public void TheVoid()
{
Console.WriteLine("In example.TheVoid");
}
}
public class Program
{
public static void TheVoid()
{
Console.WriteLine("In TheVoid");
}
public static void Main()
{
var example = new Example();
example.Method(example.TheVoid);
example.Method(() => {
Console.WriteLine("In lambda");
});
example.Method(TheVoid);
}
}
Example of what you are trying to do
Related
This question already has answers here:
How to call an appropriate method by string value from collection?
(3 answers)
Closed 3 years ago.
I have 1000 methods called method0001, method0002 , ... ,method1000.
I have a variable that takes values between 1 and 1000.
If the value of the variable is x, I'd like to call methodx. For instance, if the value of the variable is 34, I'd like to call method0034. How can I code this in C# please?
Many people are asking what is need for Methodwxyz. Every method is a different type of math question.
i've done this, following the helpful comments but am getting errors (edited the question from earlier)
using System.Collections.Generic;
using UnityEngine;
public class TextControl : MonoBehaviour
{
public static TextControl instance;
void Start()
{
instance = this;
}
// Update is called once per frame
void Update()
{
this.GetType().GetMethod("Template00" + "1").Invoke(this, null);
}
public static string Templates001()
{
// doing something here
}
}
thanks
You could do this through reflection. Edit for a quick sample (forgot invoke parameters). Some tips about reflection:
If you get a nullexception that means it can't find the method
The method you are invoking needs to be public
If you use obfuscation you may not have the same names for the method
Code
public class Program
{
public static void Main(string[] args)
{
Check method1 = new Check(1);
Check method2 = new Check(2);
}
}
public class Check
{
public Check(int x)
{
this.GetType().GetMethod("Method" + x).Invoke(this, null);
}
public void Method1()
{
Console.WriteLine("Method 1");
}
public void Method2()
{
Console.WriteLine("Method 2");
}
}
This question already has answers here:
How do I call a non-static method from a static method in C#?
(11 answers)
Closed 8 years ago.
I have the following code, I want to call data1() from data2()
private void data1()
{
}
private static void data2()
{
data1(); //generates error
}
In oder to invoke an non static method you need to create an object.
Static methods are methods on class level.
"normal" methods are on object leven.
so what you need to do in order to executer the non static method is the following:
class ClassName {
private static void data2() {
var data1Obj = new ClassName();
data1Obj.data1();
}
private void data1() {
//execute code here
}
}
but if you only use data1 in this way you could make that static to
This question already has answers here:
How do I use reflection to call a generic method?
(8 answers)
Closed 8 years ago.
I have a code like this:
if (args.ElementType == typeof(SomeFirstClassName))
{
args.Result = GetResult<SomeFirstClassName>(args);
}
else if (args.ElementType == typeof(SomeSecondClassName))
{
args.Result = GetResult<SomeSecondClassName>(args);
}
How I can simplify this code, if I will have a many types?
For example, can I do something like below?
args.Result = this.GetResult<**args.ElementType**>(args);
I cannot put the variable Type (args.ElementType) to the <>. Is it limitation of C#?
You simplify this without reflection by using a dictionary which maps the type to the method to call.
Here's a sample program to demonstrate:
using System;
using System.Collections.Generic;
namespace Demo
{
public class SomeFirstClassName{}
public class SomeSecondClassName{}
public class Result {}
public class Args
{
public Result Result;
public Type ElementType;
}
internal class Program
{
private Dictionary<Type, Func<Args, Result>> map = new Dictionary<Type, Func<Args, Result>>();
private void run()
{
init();
var args1 = new Args {ElementType = typeof(SomeFirstClassName)};
var args2 = new Args {ElementType = typeof(SomeSecondClassName)};
test(args1); // Calls GetResult<T> for Demo.SomeFirstClassName.
test(args2); // Calls GetResult<T> for Demo.SomeSecondClassName.
}
private void test(Args args)
{
args.Result = map[args.ElementType](args);
}
private void init()
{
map.Add(typeof(SomeFirstClassName), GetResult<SomeFirstClassName>);
map.Add(typeof(SomeSecondClassName), GetResult<SomeSecondClassName>);
}
public Result GetResult<T>(Args args)
{
Console.WriteLine("GetResult<T>() called for T = " + typeof(T).FullName);
return null;
}
private static void Main()
{
new Program().run();
}
}
}
This makes the call site much simpler (args.Result = map[args.ElementType](args);) but you will still have to add an initialiser for each type to the init() method, as shown above.
However this does at least move all the type logic into a single method (init()) which I think is a cleaner and more maintainable design.
However, I can't help but think that there is going to be a much better object-oriented solution to what you're trying to achieve. But we'd need a lot more information about what it is you want to do (this looks like it might be an X-Y problem at the moment).
The answer to your question is to use reflection. However, if you are looking for a non-reflection way of getting around this then you could pass in ElementType in as a parameter
GetResult<TElementType, TArgs>(TElementType elementType, TArgs args)
This would reduce your code to a single call i.e. GetResult(args.ElementType, args). It's not great but it would give you what you want.
I'm trying to pass a reference to a function as a parameter
It's hard to explain
I'll write some example pseudo code
(calling function)
function(hello());
function(pass)
{
if this = 0 then pass
else
}
hello()
{
do something here
}
Sorry if it does not make much sense
But I'm trying to reduce used code and I thought this would be a good idea.
How can I do this in C#?
You can pass code to a method by using delegates, for example, the Action delegate:
void MyFunction(Action action)
{
if (something == 0)
{
action();
}
}
void Hello()
{
// do something here
}
Usage:
MyFunction(Hello);
I'm trying to pass a reference to a function as a parameter
It's hard to explain
It may be hard to explain, but it is very easy to implement: the code below calls MyFunction passing it a parameterized piece of code as a parameter.
static void MyFunction(Action<string> doSomething) {
doSomething("world");
}
static void Main(string[] args) {
MyFunction((name) => {
Console.WriteLine("Hello, {0}!", name);
});
}
You can use delegate types provided by the system (Action and Func) or write your own.
Here is an example:
using System;
public class Example
{
public void Method1(Action hello)
{
// Call passed action.
hello();
}
public void Method2()
{
// Do something here
}
public void Method3()
{
Method1(Method2);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Retrieving the calling method name from within a method (C#)
I have a class say A in which there is a Method called Func1; this function is static.
Now there are some other classes say B, C that use A.Func1
How can I get the class name which contains the function that is calling ?
ie
public class A
{
public static void Func1()
{
// who called me?
}
}
public class B
{
public void CallFunc()
{
A.Func1();
}
}
public class C
{
public void AlsoCallFunc()
{
A.Func1();
}
}
Can use StackTrace class in order to acees that kind of information.
To get calling method name, I sometimes use this function. But you need to check if it works in your specific case:
private static string GetCallingMethodName()
{
const int iCallDeepness = 2;
System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
return sframe.GetMethod().Name;
}
if you need to work with form and want to know which form is calling then use event and sender
maybe you work with the output of
Environment.StackTrace