Why assign a method to a variable in C#? - c#

I see code written like this:
static void Main(string[] args)
{
var name = GetInfo(); //this variable contains the method below
Console.Writeline(name)
}
static string GetInfo()
{
string name = "MyName";
return (name);
}
Let's use the typical box example. What's a good example for method inside it?
In other words, what does it mean 'a value' = 'a method that does something'

Its not assigning a method, it is just getting the result of that executed method. In this way you can reuse GetInfo(); in other places where ever you need this name.

Related

How can we return a string from one method to the main method?

I am trying to call the method PrintBanner from main. However, it won't let me.
static void Main(string[] args)
{
string banner;
banner = PrintBanner("This is whats supposed to be printed.");
}
public static void PrintBanner()
{
return PrintBanner(banner);
}
I need the message to be called from main. But the error says that no overload for PrintBanner takes one argument. And that the name banner does not exist in PrintBanner.
Am I supposed to put string banner in PrintBanner method?
I'm unclear on what you are trying to accomplish here. Though it seems by your code that you want to both print and assign a value at with the PrintBanner method.
public static void Main(string[] args)
{
string banner;
banner = PrintBanner("This is whats supposed to be printed.");
}
public static string PrintBanner(string text)
{
Console.Write(text);
return text;
}
Or maybe you don't want the method itself to perform the assignment?:
public static void Main(string[] args)
{
string banner;
PrintBanner(banner = "This is whats supposed to be printed.");
}
public static void PrintBanner(string text)
{
// The text variable contains "This is whats supposed to be printed." now.
// You can perform whatever operations you want with it within this scope,
// but it won't alter the text the banner variable contains.
}
If not, then please try to elaborate further on your goal.
Oh boy... first off, your PrintBanner() method is void, therefore you won't be able to "return" anything.
Also, because your PrintBanner doesn't take any parameters, you can't pass any arguments to it.
Try this:
static void Main(string[] args)
{
string banner = PrintBanner("This is what's supposed to be printed.")
Console.WriteLine(banner);
Console.ReadLine();
}
//PrintBanner now has a string parameter named message (you can name it
//whatever you want, but in the method in order to access that parameter, the
//names have to match), thus when we call it in main, we can pass a string as
//an argument
public static string PrintBanner(string message)
{
return message;
}

C# Possible method to call protected non-static methods in current class?

I've recently picked up C# as another language to further my knowledge into other languages, but as experimenting to get used to the syntax of the language, I encountered this problem when using the public static void Main(); and calling methods inside the same class. My code was as follows:
namespace TestingProject
{
class Class1
{
public static void Main()
{
System.Console.WriteLine("This is nothing but a test \n Input 'test'");
var UserInput = System.Console.ReadLine();
string Input = this.ValidateInput(UserInput);
System.Console.WriteLine(Input);
System.Console.WriteLine();
}
protected string ValidateInput(string Variable)
{
var VarReturn = (string)null;
if (string.Equals(Variable, "test"))
{
VarReturn = "Correct \n";
}
else
{
VarReturn = "Incorrect \n";
}
return VarReturn;
}
}
}
So, from what i've researched it turns out that you cannot use the this syntax to call internal private methods from a static function.
So I tried self but this returned no avail (assuming since languages such as python, PHP allow self), so tried the following:
string Input = TestingProject.Class1.ValidateInput(UserInput);
To be presented with the following message:
Error 1 An object reference is required for the non-static field,
method, or property
'TestingProject.Class1.ValidateInput(string)' C:\Users\xxx\AppData\Local\Temporary
Projects\ClassProject\Class1.cs 14 28 ClassProject
So then, I found this little gem which did solve the problem :
var CurrClass = new Class1();
and called the protected method as so:
var CurrClass = new Class1();
string Input = CurrClass.ValidateInput(UserInput);
Which did surprise me that this was the only available way to call internal non-staic private methods, so my overall question is:
Is there a way to call non-static methods which are protected/private without initializing a new variable to contain the current object?
The problem is that your Main method is static. A static method can not access non-static methods, even within the same class, without having an instance of the object. That is the entire point of having a static method: you don't have a concrete object to work with. It's outside of the scope of the other instance methods.

Can I get the name of a method by providing the method itself?

Is there a way to get a method's name (as a string) by providing the method itself?
class Person
{
bool Eat(Food food){...}
}
I want to somehow get the string "Eat". That's all! This can either be from an instance or from the class declaration using reflection.
My attempt:
public delegate bool EatDelegate(Food f);
EatDelegate eatDel = new EatDelegate(_person1.Eat);
string methodName = eatDel.GetInvocationList()[0].Method.Name;
This requires to know the method's delegate and the whole thing is unreadable
I want the methodName in order to dynamically invoke it.
Notes:
There is a delegate declaration for every method I want to invoke
I want to avoid specifying the method's name in order to avoid errors after reflection etc
The method isn't called the moment I want to get its name. (cannot use MethodBase.GetCurrentMethod() )
I have to use .Net 3.5
public string GetName(Expression<Action> exp)
{
var mce = exp.Body as MethodCallExpression;
return mce.Method.Name;
}
--
a Method
public int MyMethod(int i)
{
return 0;
}
and usage
var s= GetName(()=>this.MyMethod(0));
var methods = typeof(Person).GetMethods();
foreach (var method in methods)
{
if (method.Name.Equals("Eat"))
{
// do something here...
}
}

Explicitly refer to a parameter

How do I explicitly refer to the parameter as opposed to the member variable?
static recursive{
public static List<string> output = new List<string>();
public static void Recursive(List<string> output){
...
}
}
An unqualified reference will always refer to the parameter because it is at a more local scope.
If you want to refer to the member variable, you need to qualify it with the name of the class (or this, for non-static member variables).
output = foo; // refers to the parameter
recursive.output = foo; // refers to a static member variable
this.output = foo; // refers to a non-static member variable
But you should probably change the name anyway. It makes your code much easier to read.
And you shouldn't have public static variables at all. All of the .NET coding style guidelines strongly recommend properties instead of exposing public fields. And since those are always camel-cased, this problem solves itself.
public static void Recursive(List<string> output){
...
}
The code in the block that refers to output will always be local & not the member variable.
If you wish to refer to member variable, you could use recursive.output.
When you are inside the Recursive static method output will point to the argument of the method. If you want to point to the static field use the name of the static class as prefix: recursive.output
Give your member variable another name.
The convention is to use Camelcasing on public static members.
public static List<string> Output = new List<string>();
public static void Recursive( List<string> output )
{
Output = output;
}
You can explicitly reference recursive.output to indicate the static member, but it would be cleaner to rename either the parameter or the member.
I know of no way to explicitly refer to a parameter. The way this is usually handled is to give member variables a special prefix such as _ or m_ so that parameters will never have exactly the same name. The other way is to refer to member variables using this.var.
public class MyClass {
public int number = 15;
public void DoSomething(int number) {
Console.WriteLine(this.number); // prints value of "MyClass.number"
Console.WriteLine(number); // prints value of "number" parameter
}
}
EDIT::
For static fields is required name of class instead of "this":
public class MyClass {
public static int number = 15;
public void DoSomething(int number) {
Console.WriteLine(this.number); // prints value of "MyClass.number"
Console.WriteLine(MyClass.number); // prints value of "number" parameter
}
}

Using MethodInfo.GetCurrentMethod() in anonymous methods

public static void Main(string[] args)
{
Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
a();
}
This code will return an obscure string like so: <Main>b__0.
Is there a way of ignoring the anonymous methods and get a more readable method name?
You could capture it outside:
var name = MethodInfo.GetCurrentMethod().Name + ":subname";
Action a = () => Console.WriteLine(name);
Other than that; no.
No, there isn't. That's why it is an anonymous method. The name is automatically generated by the compiler and guaranteed to be unique. If you want to get the calling method name you could pass it as argument:
public static void Main()
{
Action<string> a = name => Console.WriteLine(name);
a(MethodInfo.GetCurrentMethod().Name);
}
or if you really want a meaningful name you will need to provide it:
public static void Main()
{
Action a = MeaningfullyNamedMethod;
a();
}
static void MeaningfullyNamedMethod()
{
Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
}
If you are looking for getting the name of the function in which the anonymous method resides in you could travel the stack and get the name of the calling method. Do note though, that this would only work as long as your desired method name is one step up in the hierarchy.
Maybe there's a way of travelling up until you reach a non-anonymous method.
For more information see:
http://www.csharp-examples.net/reflection-calling-method-name/

Categories