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!"));
Related
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.
Is it possible to exchange implementations of methods in C#, like method swizzling in Objective-C?
So I could replace an existing implementation (from an outside source, via a dll for example) at runtime with my own (or add another onto it).
I have searched for this, but have found nothing of value.
You could use delegates to have your code point to whatever method you wish to execute at run time.
public delegate void SampleDelegate(string input);
The above is a function pointer to any method which yields void and takes a string as input. You can assign any method to it which has that signature. This can also be done at run time.
A simple tutorial can be also found on MSDN.
EDIT, as per your comment:
public delegate void SampleDelegate(string input);
...
//Method 1
public void InputStringToDB(string input)
{
//Input the string to DB
}
...
//Method 2
public void UploadStringToWeb(string input)
{
//Upload the string to the web.
}
...
//Delegate caller
public void DoSomething(string param1, string param2, SampleDelegate uploadFunction)
{
...
uploadFunction("some string");
}
...
//Method selection: (assumes that this is in the same class as Method1 and Method2.
if(inputToDb)
DoSomething("param1", "param2", this.InputStringToDB);
else
DoSomething("param1", "param2", this.UploadStringToWeb);
You can also use Lambda Expressions: DoSomething("param1", "param2", (str) => {// what ever you need to do here });
Another alternative would be to use the Strategy Design Pattern. In this case, you declare interfaces and use them to denote the behavior provided.
public interface IPrintable
{
public void Print();
}
public class PrintToConsole : IPrintable
{
public void Print()
{
//Print to console
}
}
public class PrintToPrinter : IPrintable
{
public void Print()
{
//Print to printer
}
}
public void DoSomething(IPrintable printer)
{
...
printer.Print();
}
...
if(printToConsole)
DoSomething(new PrintToConsole());
else
DoSomething(new PrintToPrinter());
The second approach is slightly more rigid than the first, but I think it is also another way to go around achieving what you want.
The only way to "replace methods" is to use delegates.
If your code looks like this:
public void Foo()
{
Bar();
}
public void Bar()
{
}
Then you cannot get Foo to call any other method than Bar. The method dispatch table you refer to in Objective-C is not mutable in .NET.
To be able to specify which method Foo should call above you need to use a delegate:
public void Foo(Action whichMethod)
{
whichMethod();
}
And you could call it like this:
Foo(Bar);
Foo(Baz);
But the method has to be built to allow this kind of runtime replacement.
While this isn't the best path to object-oriented programming in a strongly-typed language, it's worth to mention that since .NET 4.0, C# has included the Dynamic Language Runtime (DLR) which allows dynamic programming. One of most curious dynamic objects is ExpandoObject: a fully runtime-expandable object:
dynamic expando = new ExpandoObject();
expando.DoStuff = new Func<string>(() => "hello world");
// Now you can swap DoStuff with other method setting another delegate:
expando.DoStuff = new Func<string, string>(text => text + "!");
BTW, as I said above, I've shared this approach here just for learning purposes. It might be useful in some edge cases, but as C# is a compiled and strongly-typed language, you should avoid this approach in 99.99% of cases.
void Test(Action method) {
if ( method != null ) method.invoke();
}
you can call this
Test( () => { Console.WriteLine("hello world"); } )
change def and call again
Test( () => { MessageBox.Show("Hi"); } )
I don't even know how to ask this question so I'll just give the code example.
Here is the domain:
public interface ISubscriptionProvider<T>
{
void Subscribe(Action<T> callback);
}
public class Notification {}
public class CurrentUserNotifications : ISubscriptionProvider<Notification>
{
public void Subscribe(Action<Notification> callback) { }
}
Here is the method I want to make magical:
public void Subscribe<P, T>(Action<T> callback) where P : ISubscriptionProvider<T>
{
// body left out -- code uses P
}
This works, and here is how you call it:
Subscribe<CurrentUserNotifications, Notification>((n) => Console.WriteLine(n));
So the question is: Is there any way to make it callable like this:
Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));
Basically, can it infer that the action type should be just from the ISubscriptionProvider<T>.
This subscribe method lives on a static class (its a static method, I left that part out). The idea is that it will take care of constructing the ISubscriptionProvider<T> and keeping it a singleton (probably with structuremap). So in use:
Messages.Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));
Thanks!
Update:
This is kinda off topic, but if any scala people read this ...
... is be an example of a higher kinded type? Something like:
public void Subscribe<P<T>>(Action<T> callback) { }
Where P<_> is the higher kinded type?
Why can't you just use
public void Subscribe<T>(Action<T> callback)
{
}
The type P Parameter is irrelevant in your scenario as it is never used.
I have requirement in which, I have to call some initializing method before the call of any static method in the class.
Now the problem is that whenever i add new static method to that class, I forget to call that initializing method, I was wondering if there any design pattern to solve this problem. I want the initializing method is always called whenever a static method is called from the class.
AOP might be an overkill for this problem. What you may want to try is to delegate each of the static methods to another class and add the initialization code to the constructor of that class. Something like:
class StaticClass {
public static void m1 () {
new Worker().m1();
}
public static void m2 () {
new Worker().m2();
}
}
class Worker {
public Worker() {
intialize();
}
public void m1() {
// Real m1 work
}
public void m2() {
// Real m2 work
}
}
This atleast solves the problem of forgetting to put in the call to init code.
That said, this looks like: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
Can you step back and tell us why you need this?
Something like Spring AOP addresses this situation pretty well for Java. It uses AspectJ annotations to make things a little simpler, although personally I think AOP is fairly complex.
Java has static initialization blocks. Something like this:
public class SomeClass {
static {
// Your code here
}
}
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