Exchange implementations for C# methods - c#

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"); } )

Related

Can delegates wrap classes in C#?

In C++ we have the std::function type which can be used to wrap lambdas, functions and even custom classes. Here is an example of a custom class wrapped in std::function:
#include <functional>
struct A {
void operator()() {
}
};
std::function<void()> a = A();
I though the same was possible with delegates in C# but, I can not get it to work:
class Program
{
delegate void Foo();
class Bar
{
public void Invoke()
{
}
}
static void Main()
{
new Foo(new Bar()); // CS0149: Method name expected
}
}
I am convinced that this has to be possible somehow, because the delegate operator internally creates a new class that inherits from System.Delegate which suggests that I can create my own type to do the same somehow.
Simple answer is 'no' because C# doesn't have an operator() in the way C++ does.
However, a lambda can be used to store not just a function, but a function on a specific object.
class Program
{
delegate void Foo();
class Bar
{
public void Invoke()
{
}
}
static void Main()
{
var f = new Foo(new Bar().Invoke);
}
}
The difference is simply that in C# you have to specify the method name, rather than there being a default.
Also worth noting that similarly to C++, C# has generics to help this, so we can cut out the Foo declaration altogether:
var f = new Action(new Bar().Invoke);

Hook to function without delegates (Reflection)

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.

C# solving pseudocode to help understanding delegates&lambda

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!"));

What is Interface Duck Typing?

I heard the word Interface Duck Typing, but do not understand at all what is it? So I read a wiki about this and they said:
In computer programming with object-oriented programming languages, duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of an explicit interface. The name of the concept refers to the duck test.
But still could not understand what it. So I saw their program but they use dynamic keyword to call quack() & feather() function of all the classes.
I would request you all please explain in easy way what is Interface Duck Typing and how to implement in C# v2.0 because there is no dynamic keyword.
using System;
namespace DuckTyping
{
public class Duck
{
public void Quack()
{
Console.WriteLine("Quaaaaaack!");
}
public void Feathers()
{
Console.WriteLine("The duck has white and gray feathers.");
}
}
public class Person
{
public void Quack()
{
Console.WriteLine("The person imitates a duck.");
}
public void Feathers()
{
Console.WriteLine("The person takes a feather from the ground and shows it.");
}
}
internal class Program
{
private static void InTheForest(dynamic duck)
{
duck.Quack();
duck.Feathers();
}
private static void Game()
{
Duck donald = new Duck();
Person john = new Person();
InTheForest(donald);
InTheForest(john);
}
private static void Main()
{
Game();
}
}
}
C# has a nominal type system, so the compatibility of types is done based on their names. In your example you have two classes with a Quack method, however there is no way to write a method which can take instances of these two classes and invoke their Quack method.
In C# 2, the solution would be to introduce an interface and have both classes implement it:
public interface IQuack
{
void Quack();
}
public class Duck : IQuack { }
public class Human : IQuack { }
now you can create a method which take an IQuack instance and can call Human.Quack and Duck.Quack through it. In C#, methods are resolved 'early' at compile time, so you need to create a named type which supports the operations the method need so the compilation can succeed. Note there is still a runtime element to calling these methods, since the real implementation of IQuack.Quack needs to be resolved at runtime depending on the real type of the argument.
In a duck-typing system, no attempt is made to validate that a method exists before runtime. All that is required is that a given object supports the operation in that it has the right name and takes the required number of parameters (none in this case), hence the 'if it quacks like a duck' expression.
Duck typing in C# 2 can only be done using reflection, in this case you would accept an object argument and look for the required methods yourself:
public static void MakeQuack(object duck)
{
MethodInfo quackMethod = duck.GetType().GetMethod("Quack", Type.EmptyTypes, null);
if (quackMethod!=null)
{
quackMethod.Invoke(duck, new object[] { });
}
else
{
throw new ArgumentException("No Quack() method found on target");
}
}
C#4 makes this much simpler with dynamic:
public static void MakeQuack(dynamic duck)
{
duck.Quack();
}
It would say it is a way of coding where the you tell the compiler:
"Hey trust me I know what methods and properties this object supports. You don't need to check them for me whilst I code."
Once you run your app the compiler will go:
"Ok lets see if I could trust you. Let me do some runtime binding."
If you then made a mistake, such as using an unsupported method, the compiler will shout: "Hey man, this is not supported! Check my RuntimeBinderException!"
Duck typing allows an object to be passed in to a method that expects
a certain type even if it doesn’t inherit from that type. All it has
to do is support the methods and properties of the expected type in
use by the method. I emphasize that last phrase for a reason. Suppose
we have a method that takes in a duck instance, and another method
that takes in a rabbit instance. In a dynamically typed language that
supports duck typing, I can pass in my object to the first method as
long as my object supports the methods and properties of duck in use
by that method. Likewise, I can pass my object into the second method
as long as it supports the methods and properties of rabbit called by
the second method. Is my object a duck or is it a rabbit? Like the
above image, it’s neither and it’s both. In many (if not most) dynamic
languages, my object does not have to support all methods and
properties of duck to be passed into a method that expects a duck.
Same goes for a method that expects a rabbit.It only needs to support
the methods and properties of the expected type that are actually
called by the method.
Please refer this to get an idea about Duck Typing
http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx/
About Duck Typing:
We don't need to know what the object is, but we just want to let the
object do something if it can do.
Example:
Example, if here are the things that we want the following objects do.
PleaseWalk(new Dog());
PleaseRun(new Duck());
PleaseWalk(new Cup());
PleaseFly(new Man());
PleaseFly(new Bird());
And, here is the result after we request the above objects do the things.
So, we don't need to check what the object is, but we can let it do something enough. Here is the code that I have written in C#.
private void PleaseWalk(object obj)
{
string Method = "Walk";
MethodInfo walkMethod = obj.GetType().GetMethod(Method, Type.EmptyTypes, null);
if (walkMethod != null)
{
walkMethod.Invoke(obj, new object[] { });
}
else
{
Console.WriteLine(string.Format("I can not {0} because {1}", Method, WhoAreYou(obj)));
}
}
private string WhoAreYou(object unknown)
{
MethodInfo whoAreYou = unknown.GetType().GetMethod("WhoAreYou", Type.EmptyTypes, null);
return whoAreYou.Invoke(unknown, new object[] { }).ToString();
}
You can use Events and exploit C# best suitable overload functions.
Hopefully, it will be useful :)
To get something Like a duck typing (.Net 4.+):
using System.Collections;
using System.Collections.Generic;
public interface IAny
{
void InvokeGetterEvent();
}
public class AnyValueTypeDuck<T, V> : IAny
where V : AnyValueTypeDuck<T, V>
{
public static event System.Action<V> GetterEvent;
public T Data;
public void InvokeGetterEvent()
{
GetterEvent.Invoke((V)this);
}
}
// Then create some concrete classes:
// Example :
public class LifeConcreteProperty : AnyValueTypeDuck<int, LifeConcreteProperty>
{
}
public class ManaConcreteProperty : AnyValueTypeDuck<float, ManaConcreteProperty>
{
}
// Now to finally use it :
public class UserClass
{
List<IAny> allDuckTypes = new List<IAny>();
public void GetDucketTypeClass(IAny anyDuckObject)
{
LifeConcreteProperty.GetterEvent += GetDucketType;
ManaConcreteProperty.GetterEvent += GetDucketType;
anyDuckObject.InvokeGetterEvent();
// it will propagate to event and will invoke
// best suitable overload method (GetDucketType)
LifeConcreteProperty.GetterEvent -= GetDucketType;
ManaConcreteProperty.GetterEvent -= GetDucketType;
}
public void GetDucketType(LifeConcreteProperty originalClass)
{
// Your efforts go here
int value = originalClass.Data;
}
public void GetDucketType(ManaConcreteProperty originalClass)
{
// Your efforts go here
float value = originalClass.Data;
}
}

C#: Generics -- Infer the Generic Type of a Generic Type

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.

Categories