I am experiencing something weird and have a workaround already, but I don't think I understood it well.
If I call the Method below numerous times within a class:
public void Method()
{
Foo a = new Foo();
a.Delegate1Handler = ViewSomething();
}
If I call Method() multiple times in one instance of the class that it is in... I am reinitializing "a" every time but for some reason a.Delegate1Handler is still around from the previous initialization, and therefore ViewSomething() is called again and again and again....
I feel like I am forgetting something critical here?
Foo's guts look like:
public delegate void Delegate1(T t);
public Delegate1 Delegate1Handler { get; set; }
EDIT: (workaround that I put in is described below, but I still don't understand exactly why it was behaving like this) ->
Initialized "a" and it's delegate1Handler outside of "Method" where delegate1Handler only gets initialized once and "a" can again get reinitialized - no problem! (or maybe it is I don't know)
a.Delegate1Handler = ViewSomething();
To me, this suggests that ViewSomething() is a method that returns a delegate.
ViewSomething() would be called every time you run Method()
I think #hans was getting at something like this in his comment
public void Method()
{
Foo a = new Foo( ViewSomething );
}
// ...
public class Foo
{
public Foo( Delegate1 del ) // note: accepting the delegate parameter
{
DelegateHandler = del;
}
}
public delegate void Delegate1(T t);
public Delegate1 Delegate1Handler { get; set; }
Related
I'll start with a code example. I have a following class
public class Foo
{
public object DoSomething() {}
}
I also have some code that utilises method DoSomehting from class Foo.
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
foo.DoSomething();
...
foo.DoSomething();
}
}
How could I distinguish those two calls foo.DoSomething() inside the Foo class?
What I came up with is to have an identification object passed in parameters for each call to DoSomething. Then in Foo class I would store the ids and compare them when new call is made.
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
var idObjA = new IDObj(Guid.NewGuid());
foo.DoSomething(idObjA);
...
var idObjB = new IDObj(Guid.NewGuid());
foo.DoSomething(idObjB);
}
}
Maybe there is a better way to do it, or a pattern that I'm not aware of. I want the utilising code to be the least obscured so calls to the DoSomething method are as simple as possible.
To clarify my intentions. I'm implementing a message service with an ability for the user to check a checkbox on dialog box (e.g. Do not show again, or Apply to all). Code utilising the service can call the same method multiple times, to show an error message for example, but in different context. In other words, when user decided to not show that message again for particular action message box should not appear. Thus I need to know when method was called multiple times in the same context (action)
Maybe you should expand a bit on what exactly you are trying to achieve. If you're using your instantiated class like described above and are just trying to differentiate between the first and second call, you can add a respective toggle field in your Foo class:
public class Foo
{
private bool _firstCall = true;
public object DoSomething() {
if(_firstCall) {
_firstCall = false;
// first call logic
} else {
// second call logic
}
}
}
Based on the extra info in your edit, it sounds like what you perhaps need to be doing is setting a separate property in your Foo class showing whether the "apply to all" or "do not show again" option has been checked for a particular context.
Then when you call DoSomething, it can check that property to know if it should show the dialog or not.
So in the simplest case you might do something like:
public class Foo
{
public bool DoNotShow { get; set; };
public void DoSomething() {
if(this.DoNotShow == true) {
// logic
} else {
// alternative logic
}
}
}
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
foo.DoSomething();
foo.DoNotShow = true;
...
foo.DoSomething();
}
}
The value could then be toggled on and off whenever you like.
N.B. You mentioned different "contexts" in which dialogs can be turned on and off.
For this, you could consider either giving this property the ability to store values for different contexts (e.g. in something like a Dictionary, perhaps) and then passing in the current context name to the DoSomething method when it's called. Or even pass in a totally separate "context" object to DoSomething each time, which contains the context name and the boolean indicating whether to show the dialog or not.
Or...using a different instance of Foo for each context might actually be more in line with object-oriented principles (in which case you could probably use the code exactly as per my example above). Again it depends exactly how the class the and the overall application works.
If knowing the line number of the call helps, you could use one of the methods for getting the caller information described here. So for example:
public class Foo
{
public object DoSomething() {
StackFrame frame = new StackFrame(1, true);
var method = frame.GetMethod();
var lineNumber = frame.GetFileLineNumber();
}
}
Is there a way I could use reflection to hook one function to another without using delegates?
class A
{
void Foo()
{
}
}
class B
{
void Main()
{
A a = new A();
a.GetType().GetMethod("Foo").AddHook(a, Func); //I want something like this
a.Foo();
//Func gets called
}
void Func()
{
}
}
Is there a way to call Func after Foo was called without using events, delegates or just calling Func from inside Foo?
I need this so my game's UI controller can get updated.
The way I see most people dealing with this is by adding a bunch of events to A and subscribing B to those. Like this
class A
{
public delegate void UICallback();
public event UICallback onFoo;
void Foo()
{
onFoo.Invoke();
}
}
class B
{
void Main()
{
A a = new A();
a.onFoo += Func;
a.Foo();
}
void Func()
{
}
}
The problem I find with this approach is that I'd need to add a bunch of events like these (probably more than 5 or even 10) to many classes and then remember to invoke those at the end of a function to update UI (invoke onBattleStarted at the end of StartBattle(), for example). This, in addition to increasing the size of my classes with big blocks of event declarations making it ugly to read, makes it a harder maintain.
EDIT I think no one really understands what I'm looking for... I'd like a way to hook Func to Foo without making any changes to Foo, i.e. without Foo knowing this callback exists. Using an action won't help since I'd need specify on Foo's parameters that it should call Func
Thank you for your help!
You Can call Action at the end of Func().
Class A
{
void Foo()
{
}
}
Class B
{
void Main()
{
A a = new A();
Func( () => {a.Foo();});
}
void Func(Action onFinish)
{
//Enter your code here
onFinish();
}
There is the method chaining pattern if that can solve your problem:
namespace Assets
{
public class Example
{
public Example GrabSomeFoodInTheFridge()
{
// some work
return this;
}
public Example WatchTv()
{
// some work
return this;
}
public Example EatFood()
{
// some work
return this;
}
}
public class Demo
{
public Demo()
{
var example = new Example();
var instance = example
.GrabSomeFoodInTheFridge()
.EatFood()
.WatchTv();
}
}
}
It does not use reflection at all, additionally you could leverage interfaces and extension methods.
Can I call a constructor from same class method in C#?
Example:
class A
{
public A()
{
/* Do Something here */
}
public void methodA()
{
/* Need to call Constructor here */
}
}
The short answer is No :)
You cannot call constructors as simple methods except these special cases:
You create a new object: var x = new ObjType()
You call a constructor from another constructor of the same type:
class ObjType
{
private string _message;
// look at _this_ being called before the constructor body definition
public ObjType() :this("hello")
{}
private ObjType(string message)
{
_message = message;
}
}
You call a base type constructor from a constructor:
class BaseType
{
private string _message;
// NB: should not be private
protected BaseType(string message)
{
_message = message;
}
}
class ObjType : BaseType
{
// look at _base_ being called before the constructor body execution
public ObjType() :base("hello")
{}
}
UPD. Regarding the workaround with an initialization method proposed in another answer - yes, it's probably a good way. But it's a bit tricky because of the object consistency, which is the reason why constructors are even exist. Any object method is expected to receive the object (this) in a consistent (working) state. And you cannot guarantee it calling a method from a constructor. So any person editing that initialization method or calling constructor in future (probably you) could expect having this guarantee which greatly increases the risk of making mistake. The problem is amplified when you deal with inheritance.
Besides provided answer which answers the question, an easy away to fix your problem is to define an initialization method that is called from both the constructor and your method:
class A
{
private init()
{
// do initializations here
}
public A()
{
init();
}
public void methodA()
{
// reinitialize the object
init();
// other stuff may come here
}
}
Shortly put, you cannot call the constructor, but you don't have to :)
I have trouble understanding lambdas, delegates and so on, I hope with someone giving me a solution to my problem I am able to understand those better. Basically it is possible to create (or change) the body of a method when an object of the class is initialized, no?
Kinda like this:
Let's say I have 1 classes: Class A, which looks like this:
public class ClassA{
int i;
public ClassA(int number)
{
i = number;
}
public void Foo(){}
}
For demonstration purposes very minimalistic, now I also have somewhere else the static main, and what I want to do there is following: Creating multiple objects of ClassA and make it so that when I call ClassA.Foo I get different results I can determine myself, how is it supposed to look Syntax wise?
static void Main(string[] args)
{
ClassA FooBlue = New ClassA(1){
public void Foo()
{
System.Console.WriteLine("I am a Fooranger Blue!");
};
ClassA FooPink = New ClassA(2){
public void Foo()
{
System.Console.WriteLine("My color is the manliest!");
};
...
So now when I do this:
...
FooBlue.Foo();
FooPink.Foo();
System.Console.ReadLine();
}
I get following output on the console:
"I am a Fooranger Blue!"
"My color is the manliest!"
I just mention again that this is an example and by no means anything out of praxis but for the purpose of me understanding that stuff it would be great if someone can provide an answer that gives the desired solution, including the useless integer i.
To accomplish the goal of "providing the implementation of a method when constructing the type" you can indeed use delegates. Simply accept a delegate when constructing the object and invoke it when you want it to be executed:
public class ClassA
{
private Action action;
public ClassA(Action action)
{
this.action = action;
}
public void Foo()
{
action();
}
}
The syntax for a lambda is different than the syntax for creating a named method from a class' definition:
var fooBlue = new ClassA(() => Console.WriteLine("I am a Fooranger Blue!"));
In C# is it possible to create a function that can only be called from within another function?
e.g., can you do something like this?
private void a()
{
b();
c();
...do something else
private void b()
{
..do something but can only be called from a()
}
private void c()
{
..do something but can only be called from a()
}
}
The reason I want to do this is that function b() and c() split some implentation details of a() and they are just cleaner and easier to read in their own scope. However, these functions are of no use to the class as a() does some handling after they are called which must take place.
Use an anonymous nested function maybe?
I wouldn't worry about taking explicit steps to ensure b() and c() are only called by a().
It makes sense to worry about the public methods you expose on a class, since you're providing an interface to the outside world, potentially to people who don't have access to the source code of your class (or at the very least don't want to worry about the implementation details of your class).
Inside your class, though, you should feel free to have whatever private methods you want for whatever reasons you want. Code re-use is one reason to create a new private method, but creating multiple smaller, single-use methods to break up a larger one is also a perfectly valid (and common) reason.
Beyond that, for future maintainers of your code a simple comment like:
//this method should only be called by a()
private void b()
{
...
}
is going to be far more understandable than most of the other solutions presented here.
Using a delegate you can do:
public voidMyFunction()
{
Func<string> myFunction=(s)=>Console.WriteLine(s);
foreach(string str in myStringList)
{
myFunction(str);
}
}
The short answer is no; however, you can create an anonymous delegate or lambda expression as your internal b() method.
You could use the StackFrame class to check at runtime who's the caller of the function:
public class MyClass
{
public static void A()
{
B();
}
public static void B()
{
var stackTrace = new StackTrace();
if (stackTrace.FrameCount < 1 || stackTrace.GetFrame(1).GetMethod() != typeof(MyClass).GetMethod("A"))
throw new InvalidOperationException("Not called from A()");
}
}
But that is
1) Only at runtime
2) Slow
3) A really dirty hack
Well you could use reflection and just get the calling method name and throw an exception if it were anything other than A.
http://www.csharp-examples.net/reflection-calling-method-name/
But if b and c are private they can only be called from within that class anyway, and if you're the only one that is writing the class, then i fail to see the problem. So it seems to me its not a coding problem but rather one of policy.
I'd just document the intent in the method headers/comments.
Similar Question Here - Note the comments on the answer
Not exactly but you could implement both within their own class. Mark b() as private.
To gain the effect of only a() calling b(), either do as Andrew noted already, by putting a() and b() in a class and marking b() appropriately. If you're working inside of an assembly that you control totally, you could use internal instead of private if a() and b() will be in different classes, but in the same assembly. Then user code cannot call it (from outside of your assembly, that is, from their application program) and you can control via policy the writing of your assembly.
You can also create something like this:
internal abstract class SecretFunctionWrapper
{
private void MySecretFunction()
{
...
}
protected void FunctionWhichCalls()
{
...
MySecretFunction();
}
}
public MyRealClass : SecretFunctionWrapper
{
...
}
This will work only for one function. You can also try nested private class like this:
public class A
{
private static class Wrapped
{
private static void A()
{
secred code
}
public static void B()
{
A();
}
}
public void UsingA()
{
Wrapped.B();
}
}
i dont know but maybe Code by Contracts may help but this is not supported natively
Maybe easier to use #region in this case
You could use the internal keyword and put both those functions inside the same class, while leaving other other functions in a different class:
http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx