Edit: Thank you for the answers. I am currently working on it!!\
I have 3 methods, S() returns string, D() returns double and B() returns bool.
I also have a variable that decides which method I use. I want do this:
// I tried Func<object> method; but it says D() and B() don't return object.
// Is there a way to use Delegate method; ? That gives me an eror saying method group is not type System.Delegate
var method;
var choice = "D";
if(choice=="D")
{
method = D;
}
else if(choice=="B")
{
method = B;
}
else if(choice=="S")
{
method = S;
}
else return;
DoSomething(method); // call another method using the method as a delegate.
// or instead of calling another method, I want to do:
for(int i = 0; i < 20; i++){
SomeArray[i] = method();
}
Is this possible?
I read this post: Storing a Method as a Member Variable of a Class in C# But I need to store methods with different return types...
Fortunately, we can store a method's return value into a variable. Take a look at the following code: int num = 7; int tenAdded = addTen(7); First, we create a variable named num and initialize it to 7.
We refer to non-void methods that return an attribute value as getter methods. When you use a method that returns a value, you need to save what it returns in a variable or use the value in some way for example by printing it out. The data type of the variable must match the data type of the return value of the method.
Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() . If we need to pass the actual method as an argument, we use the lambda expression.
You can't. Variables defined inside a method are local to that method. If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Func<object> method;
var choice = "D";
if(choice=="D")
{
method = () => (object)D;
}
else if(choice=="B")
{
method = () => (object)B;
}
else if(choice=="S")
{
method = () => (object)S;
}
else return;
DoSomething(method); // call another method using the method as a delegate.
// or instead of calling another method, I want to do:
for(int i = 0; i < 20; i++){
SomeArray[i] = method();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With