can I self reference from within a method, without using the method name (for code maintenance reasons this may cause a future bug)
void SelfRef(string _Input){
if (_Input == "route1"){
//route1 calls route 2
SelfRef("route2"); //call self
}else if (_Input == "route2"){
//route2 ends
}
}
i would like to not write the word "SelfRef" again and make the function immune to future changes?
I would like to not write the word "SelfRef" again and make the function immune to future changes?
As others have said, you should simply use renaming tools if you are planning to rename a method.
But it is an interesting challenge to make a recursive function that does not refer to the name of the function. Here's a way to do it:
delegate Action<A> Recursive<A>(Recursive<A> r);
static Action<A> AnonymousRecursion<A>(Func<Action<A>, Action<A>> f)
{
Recursive<A> rec = r => a => { f(r(r))(a); };
return rec(rec);
}
Action<string> SelfRef = AnonymousRecursion<string>(
f =>
input =>
{
if (input == "route1")
f("route2");
// and so on
});
Notice how field SelfRef nowhere refers to SelfRef in its body, and yet the recursion is very straightforward; you simply recurse on f instead of SelfRef.
However I submit to you that this code is far, far harder to understand and maintain than simply writing a straightforward recursive method.
Yes, it's possible:
void Foo(int bar)
{
Console.WriteLine(bar);
if(bar < 10)
MethodBase.GetCurrentMethod().Invoke(this, new object[] {++bar});
else
Console.WriteLine("Finished");
}
but please never ever use code like this (it's ugly, it's slow, it's hard to understand, it will not work if the method is inlined).
Since you probably use an IDE like Visual Studio, renaming a method should never ever be an issue; and even if you rename the method manually you probably hit a compile time error.
You can create extension like this
public static void RecursivelyCall(this object thisObject, object [] param, [System.Runtime.CompilerServices.CallerMemberName] string methodName = "")
{
Type thisType = thisObject.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(thisObject, param);
}
public static void RecursivelyCall(this object thisObject, object param, [System.Runtime.CompilerServices.CallerMemberName] string methodName = "")
{
Type thisType = thisObject.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(thisObject, new object[] {param});
}
So you can use it for recursive call
private void Rec(string a)
{
this.RecursivelyCall(a);
}
But, to be honest, i don't think it is a good idea, because
function immune to future changes
doesn't worth losing code readability.
Now let's just make it clear that the technical term for "self-referencing" is recursion. And let's start looking at the problem.
You want to write a recursive method but don't want to "mention" the method name because of maintainability reasons. When I saw this I was like, "what editor are you using?". Maintainability reasons? You mean when you change the name of the method the code breaks?
These problems ca be easily fixed by using an IDE. I suggest you to use Visual Studio Community 2015. It is free and offers a wide range of features. If you want to rename a method, do this:
Right click the method name.
Select "Rename" in the context menu
Type whatever name you want it to be.
Press Enter
And you will see that magically, all the references to the method has changed their names!
So you don't need to turn the whole recursive method into a loop or something. You just need to use the right editor!
Self referencing (probably via reflection) and recursing seems quite long winded when a loop would be sufficient here:
void SelfRef(string _Input){
while(true)
{
if (_Input == "route1"){
_Input = "route2"
continue;
}else if (_Input == "route2"){
//route2 ends
break;
}
//break?
}
}
There's no construct in C# to refer to the method that you're in and call it with different parameters. You could examine the call stack to find the method name and use reflection to invoke it, but it seems pointless.
The only type of bug that you would be "immune" to is renaming the method. In that case, the build will fail and you will quickly have an indication that something is wrong.
It is possible using reflection using MethodBase.GetCurrentMethod() and it's the fastest way that I know of. Certainly faster than using Stacktraces.
You can change your code as follows:
void SelfRef(string _Input){
if (_Input == "route1"){
//route1 calls route 2
MethodBase.GetCurrentMethod().Invoke(this,new []{"route2"}); //call self
}else if (_Input == "route2"){
//route2 ends
}
}
Don't forget using System.Reflection namespace.
You are using recursion, not self reference
A function (method) calling itself is called as a recursive function and this concept is called as recursion. What you essentially have, is a recursive function called as SelfRef that takes a string as a parameter. It calls itself if the parameter is equal to "route1" which is a string.
Method reference is passing a method to another method
Method references (as called in other languages) is called as delegates in C# and that is used to pass a function itself to another function. This is mostly used to implement callbacks, i.e., event handlers. For example, you might see this code in events.
public class DelegateExample
{
public delegate void MyDelegate();
public void PrintMessage(MyDelegate d)
{
d();
}
public void PrintHello()
{
Console.WriteLine("Hello.");
}
public void PrintWorld()
{
Console.WriteLine("World.");
}
public static void Main(string[] args)
{
PrintDelegate(new MyDelegate(PrintHello));
PrintDelegate(new MyDelegate(PrintWorld));
}
}
There you see, you are passing a function as a delegate.
Use enums if you know what routes are available already
Never use strings for communicating between objects or withing the program, only use them for interacting with the user. The best bet (if the routes are pre-known) at the time of writing the program, then use enumerations for this purpose.
Calling a function by name does not cause a code-maintenance problem.
All modern development environments (e.g. Visual Studio) will automatically update every usage of that function's name, when someone renames it.
If you want to make the function immune from future changes, keep the source code to yourself.
Related
I have several methods that have the folling structure:
public void doWhatever()
{
methodToPrepareEnvironment();
// do something
methodToResumeEnvironment();
}
All my "doWhatever"-type methods call these prepare/resume methods and there is only 1 prepare and 1 resume method called by all these doWhatever methods. Is there a better way to achieve this without having to put a call to the prepare and resume methods at the beginning and end of all my doWhatever methods? I have the feeling I am missing something extremely basic here. Please note, the doWhatever methods cannot be combined, they each need to be independent and they each need to prepare the environment, do some tasks and then resume the environment.
Thank you.
With strategic use of access modifiers you can ensure external calls are always preceded and followed by method calls with little repetition like so:
public void DoWhatever()
{
DoAction(DoingWhatever);
}
private void DoingWhatever()
{
// ...
}
private void DoAction(Action action)
{
methodToPrepareEnvironment();
action();
methodToResumeEnvironment();
}
An Action is a delegate that represents a method with no return value.
Is there a better way to achieve this without having to put a call to the prepare and resume methods at the beginning and end of all my doWhatever methods?
Pass in a delegate (two built in ones are Action and Func):
public void doWhatever(Action anAction )
{
methodToPrepareEnvironment();
anAction();
methodToResumeEnvironment();
}
In regards of ensuring the Prepare and Resume are always called - the above does not cater for that, as the anAction can be called by any code that has access to it.
You can investigate AOP - a popular tool is PostSharp.
This how I would do it , Introduce a delegate that has the signature of the function to be called between methodToPrepareEnvironment() and methodToResumeEnvironment() and then attach the funcion to the delegate and call doWhatever in this way
doWhatever(Fn);
//////
public delegate void ToDO();
class Program
{
public void Fn()
{
Console.WriteLine("This is Fn");
}
public void doWhatever(ToDO t)
{
methodToPrepareEnvironment();
t();
methodToResumeEnvironment();
}
}
A slightly different option (though not as "clean" as these options, and certainly not as intuitive to someone trying to maintain the code would be to mark the functions with an attribute, and then have a build step that injects method calls before and after:
[WrapWithEnvironmentCalls()]
public void MyFunction()
{
// Code goes here
}
I believe the CTP Rosalyn has some functionality to approach this.
CAVEAT: I would never do this in my code, it wouldn't be maintainable, intuitive, and would likely get torn to shreds in a code review, but I'm just providing it as an alternate option for those more adventurous.
I've read two books, tons of examples. They still make next to no sense to me. I could probably write some code that uses delegates, but I have no idea why. Am I the only one with this problem, or am I just an idiot? If anyone can actually explain to me when, where, and why I would actually use a delegate, I'll love you forever.
Delegates are just a way to pass around a function in a variable.
You pass a delegated function to do a callback. Such as when doing asynchronous IO, you pass a delegated function (a function you have written with the delegate parameter) that will be called when the data has been read off the disk.
As other people have mentioned delegates are handy for callbacks. They're useful for a whole load of other things too. For example in a game I've been working on recently bullets do different things when they hit (some do damage, some actually increase the health of the person they hit, some do no damage but poison the target and so on). The classical OOP way to do this would be a base bullet class and a load of subclasses
Bullet
DamageBullet
HealBullet
PoisonBullet
DoSomethingElseBullet
PoisonAndThenHealBullet
FooAndBarBullet
....
With this pattern, I have to define a new subclass every time I want some new behavior in a bullet, which is a mess and leads to a lot of duplicated code. Instead I solved it with delegates. A bullet has an OnHit delegate, which is called when the bullet hits an object, and of course I can make that delegate anything I like. So now I can create bullets like this
new Bullet(DamageDelegate)
Which obviously is a much nicer way of doing things.
In functional languages, you tend to see a lot more of this kind of thing.
A delegate is a simple container that knows where in the machine's memory a specific method is located.
All delegates have an Invoke(...) method, thus when someone has a delegate, he can actually execute it, without really having to know or bother what that method actually does.
This is especially helpful for decoupling stuff. GUI frameworks wouldn't be possible without that concept, because a Button simply can't know anything about your program you're going to use it in, so it can't call your methods by itself whenever it is clicked. Instead, you must tell it which methods it should call when it is clicked.
I guess you're familiar with events and you do use them regularly. An event field is actually a list of such delegates (also called a multi-cast delegate). Maybe things will become clearer when we look at how we could "simulate" events in C# if it didn't have the event keyword, but only (non-multicast) delegates:
public class Button : Rectangle
{
private List<Delegate> _delegatesToNotifyForClick = new List<Delegate>();
public void PleaseNotifyMeWhenClicked(Delegate d)
{
this._delegatesToNotifyForClick.Add(d);
}
// ...
protected void GuiEngineToldMeSomeoneClickedMouseButtonInsideOfMyRectangle()
{
foreach (Delegate d in this._delegatesToNotifyForClick)
{
d.Invoke(this, this._someArgument);
}
}
}
// Then use that button in your form
public class MyForm : Form
{
public MyForm()
{
Button myButton = new Button();
myButton.PleaseNotifyMeWhenClicked(new Delegate(this.ShowMessage));
}
private void ShowMessage()
{
MessageBox.Show("I know that the button was clicked! :))))");
}
}
Hope I could help a little. ;-)
Maybe this helps:
A delegate is a type (defining a method signature)
A delegate instance is a reference to a method (AKA function pointer)
A callback is a parameter of a delegate-type
An event is a (kind of) property of a delegate-type
The purpose of delegates is that you can have variables/fields/parameters/properties(events) that 'hold' a function. That lets you store/pass a specific function you select runtime. Without it, every function call has to be fixed at compile time.
The syntax involving delegates (or events) can be a bit daunting at first, this has 2 reasons:
simple pointer-to-functions like in C/C++ would not be type-safe, in .NET the compiler actually generates a class around it, and then tries to hide that as much as possible.
delegates are the corner-stone of LINQ, and there is a steep evolution from the specify-everything in C#1 through anonymous methods (C#2) to lambdas (C#3).
Just get acquainted with 1 or 2 standard patterns.
Come on Guys! All of you successfully complicated the DELEGATES :)!
I will try to leave a hint here : i understood delegates once I realized jquery ajax calls in Javascript. for ex: ajax.send(url, data, successcallback, failcallback) is the signature of the function. as you know, it sends data to the server URL, as a response, It might be 200OK or some other error. In case of any such event(success/fail), you want to execute a function. So, this acts like a placeholder of a function, to be able to mention in either success or failure.
That placeholder may not be very generic - it might accept a set of parameters and may/may not return value. That declaration of such Placeholder, if done in C# IS CALLED DELEGATE! As javascript functions not strict with number of arguments, you would just see them as GENERIC placeholders...but C# has some STRICT declarations... that boils down to DELEGATE declarations!!
Hope it helps!
Delegate is a type safe function pointer, meaning delegate points to a function when you invoke the delegate function the actual function will be invoked. It is mainly used when developing core application framework. When we want to decouple logic then we can use delegate. Ie instead of hand coding logic in a particular method we can pass the delegate to the function and set different function logic inside the delegate function. Delegates adds flexibility to your framework.
Example: how to use it
class Program
{
public static void Main()
{
List<Employee> empList = new List<Employee>() {
new Employee () {Name = "Test1", Experience = 6 },
new Employee () {Name = "Test2", Experience = 2 },
};
// delegate point to the actual function
IsPromotable isEligibleToPromote = new IsPromotable(IsEligibleToPromoteEmployee);
Employee emp = new Employee();
// pass the delegate to a method where the delegate will be invoked.
emp.PromoteEmployee(empList, isEligibleToPromote);
// same can be achieved using lambda empression no need to declare delegate
emp.PromoteEmployee(empList, emply => emply.Experience > 2);
Console.ReadKey();
}
// this condition can change at calling end
public static bool IsEligibleToPromoteEmployee(Employee emp)
{
if (emp.Experience > 5)
return true;
else
return false;
}
}
public delegate bool IsPromotable(Employee emp);
public class Employee
{
public string Name { get; set; }
public int Experience { get; set; }
// conditions changes it can 5, 6 years to promote
public void PromoteEmployee(List<Employee> employees, IsPromotable isEligibleToPromote)
{
foreach (var employee in employees)
{
// invoke actual function
if (isEligibleToPromote(employee))
{
Console.WriteLine("Promoted");
}
}
}
}
Using C#, I need to do some extra work if function A() was called right before function C(). If any other function was called in between A() and C() then I don't want to do that extra work. Any ideas that would require the least amount of code duplication?
I'm trying to avoid adding lines like flag = false; into every function B1..BN.
Here is a very basic example:
bool flag = false;
void A()
{
flag = true;
}
void B1()
{
...
}
void B2()
{
...
}
void C()
{
if (flag)
{
//do something
}
}
The above example was just using a simple case but I'm open to using something other than booleans. The important thing is that I want to be able to set and reset a flag of sorts so that C() knows how to behave accordingly.
Thank you for your help. If you require clarification I will edit my post.
Why not just factor your "Extra work" into a memoised function (i.e. one that caches its results)? Whenever you need that work you just call this function, which will short circuit if the cache is fresh. Whenever that work becomes stale, invalidate the cache. In your rather odd examples above, I presume you'll need a function call in each of the Bs, and one in C. Calls to A will invalidate the cache.
If you're looking for away around that (i.e. some clever way to catch all function calls and insert this call), I really wouldn't bother. I can conceive of some insane runtime reflection proxy class generation, but you should make your code flow clear and obvious; if each function depends on the work being already done, just call "doWork" in each one.
Sounds like your design is way too tightly coupled if calling one method changes the behavior of another such that you have to make sure to call them in the right order. That's a major red flag.
Sounds like some refactoring is in order. It's a little tricky to give advice without seeing more of the real code, but here is a point in the right direction.
Consider adding a parameter to C like so:
void C(bool DoExtraWork) {
if (DoExtraWork)...
}
Of course "DoExtraWork" should be named something meaningful in the context of the caller.
I solved a problem with a similar situation (i.e., the need to know whether A was called directly before C) by having a simply state machine in place. Essentially, I built a state object using an enum and a property to manage/query the state.
When my equivalent of A() was called, it would have the business logic piece store off the state indicating that A was called. If other methods (your B's ) were called, it would toggle the state to one of a few other states (my situation was a bit more complicated) and then when C() was called, the business logic piece was queried to determine if we were going to call some method D() that held the "only if A was just called" functionality.
I suspect there are multiple ways to solve this problem, but I liked the state machine approach I took because it allowed me to expand what was initially a binary situation to handle a more complicated multi-state situation.
I was fortunate that multi-threading was not an issue in my case because that tends to make things more entertaining, but the state machine would likely work in that scenario as well.
Just my two cents.
I don't recommend this, but what the hell: If you're willing to replace all your simple method calls:
A();
... with syntax like this:
// _lastAction is a class-level Action member
(_lastAction = new Action(A)).Invoke();
... then inside of C() you can just do a check like this:
void C()
{
if (_lastAction.Method.Name == "A")
{
}
}
This probably isn't thread-safe (and it wouldn't work in code run through an obfuscator without a bit of tinkering), so I wouldn't use something like this without heavy testing. I also wouldn't use something like this period.
Note: my ancient version of C# only has Action<T> (and not Action or Action<T, T> etc.), so if you're stuck there, too, you'd have to add a dummy parameter to each method to use this approach.
Very often it happens that I have private methods which become very big and contain repeating tasks but these tasks are so specific that it doesn't make sense to make them available to any other code part.
So it would be really great to be able to create 'inner methods' in this case.
Is there any technical (or even philosophical?) limitation that prevents C# from giving us this? Or did I miss something?
Update from 2016: This is coming and it's called a 'local function'. See marked answer.
Well, we can have "anonymous methods" defined inside a function (I don't suggest using them to organize a large method):
void test() {
Action t = () => Console.WriteLine("hello world"); // C# 3.0+
// Action t = delegate { Console.WriteLine("hello world"); }; // C# 2.0+
t();
}
If something is long and complicated than usually its good practise to refactor it to a separate class (either normal or static - depending on context) - there you can have private methods which will be specific for this functionality only.
I know a lot of people dont like regions but this is a case where they could prove useful by grouping your specific methods into a region.
Could you give a more concrete example? After reading your post I have the following impression, which is of course only a guess, due to limited informations:
Private methods are not available outside your class, so they are hidden from any other code anyway.
If you want to hide private methods from other code in the same class, your class might be to big and might violate the single responsibility rule.
Have a look at anonymous delegates an lambda expressions. It's not exactly what you asked for, but they might solve most of your problems.
Achim
If your method becomes too big, consider putting it in a separate class, or to create private helper methods. Generally I create a new method whenever I would normally have written a comment.
The better solution is to refactor this method to separate class. Create instance of this class as private field in your initial class. Make the big method public and refactor big method into several private methods, so it will be much clear what it does.
Seems like we're going to get exactly what I wanted with Local Functions in C# 7 / Visual Studio 15:
https://github.com/dotnet/roslyn/issues/2930
private int SomeMethodExposedToObjectMembers(int input)
{
int InnerMethod(bool b)
{
// TODO: Change return based on parameter b
return 0;
}
var calculation = 0;
// TODO: Some calculations based on input, store result in calculation
if (calculation > 0) return InnerMethod(true);
return InnerMethod(false);
}
Too bad I had to wait more than 7 years for this :-)
See also other answers for earlier versions of C#.
Question
I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?
If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.
Code
// Finds calling method from class that called into this one
public class SomeClass
{
public static void FindMethod()
{
for (int i = 1; i < frameCount; i++)
{
var frame = new StackFrame(i);
var methodInfo = frame.GetMethod();
if (methodInfo.DeclaringType != this.GetType())
{
string methodName = frame.GetMethod().Name;
var paramInfos = methodInfo.GetParameters();
// Now what?? How do I get the values from the paramInfos
break;
}
else if (i == frameCount - 1)
{
throw new TransportException("Couldn't find method name");
}
}
}
}
You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even that the parameter passed is not in fact what the method signature would suggest (it is perfectly possible for an optimizing JIT compiler to spot that you are only using a sub field of an object/struct and pass that instead).
The ParameterInfo simply tells you the signature of the method as compiled, not the values that were passed.
The only realistic way to achieve this automatically is via code injection (via something like AOP) to create the data and do what you want with it based on analysing the IL.
This is generally not a good idea, if you need to debug something use a debugger, if you need to log something be explicit about what you are logging.
To be clear simple reflective techniques cannot achieve what you desire with full generality
Jonathan Keljo at Microsoft says, in this news group post, :
Unfortunately, the only easy way to get argument information from a
callstack today is with a debugger. If you're trying to do this as part of
error logging in an application and you plan to send the error log back to
your support department, we're hoping to have you use minidumps for that
purpose in the future. (Today, using a minidump with managed code is a
little problematic as it does not include enough information to even get a
stack trace by default. A minidump with heap is better, but not so "mini"
if you know what I mean.)
A purist would say that allowing people to write code that can get
arguments from functions elsewhere on the callstack would encourage them to
break encapsulation and create code that's very fragile in the face of
change. (Your scenario does not have this particular problem, but I've
heard other requests for this feature that would. Anyway most of those
requests can be solved in other ways, like using thread stores.) However,
more importantly there would be security implications of this--applications
that allow plugins would be at risk of those plugins scraping the stack for
sensitive information. We could certainly mark the function as requiring
full-trust, but that would make it unusable for pretty much every scenario
I've heard of.
Jonathan
So... I guess the short answer is "I can't." That sucks.
Yes, you can do this.
What you need to do is use an IL disassembler (which is achievable within the System.Reflection.Emit namespace) to find the Operand that contains the parameter value you're looking for.
Start with this SO question: C# reflection and finding all references
Then use the class mentioned in the answers (from Mono.Reflection) to do your inspection. Something like this:
var instructions = method.GetInstructions();
foreach (var instruction in instructions)
{
var methodInfo = instruction.Operand as MethodInfo;
if(methodInfo == null)
{
continue;
}
if (instruction.OpCode.Name.Equals("call") && methodInfo.Name.Equals("YourMethodHere"))
{
var value = (CastToMyType)instruction.Previous.Operand;
// Now you have the value...
}
}
You can't do it with either StackFrame or StackTrace. You can, however, employ some interception framework (such as AOP stuff from Spring.NET) so that you can get hold of parameter values.
See here:
Can you get a list of variables on the stack in C#?
I don't think it's possbile, based on all the comments on my answer there. The PropertyInfo class does have a GetValue method, but that requires you to have an actual object of which you want to get the value from.
Not sure if this counts as a solution, but worked for a specific case that i had,
i wanted to log each time a float was modified with minimal code changes,
Reading the file on the stack trace line to figure out the params
public static Score operator +(Score x,float y) {
var st = new StackTrace(true);
var sf = st.GetFrame(1);
string paramName = File.ReadLines(sf.GetFileName()).ElementAtOrDefault(sf.GetFileLineNumber()-1).Split(new[] { "+=" }, StringSplitOptions.None)[1];
x.DebugString += (paramName+" "+y);
x.DebugString += System.Environment.NewLine;
x.val += y;
return x;
}
void Main(){
Score score = new Score();
float firstScore = 2;
float secondScore = -13;
score+=firstScore;
score+=secondScore;
Console.WriteLine(score.DebugString);
}
Output :
firstscore 2
secondScore -13