C# Delegate Instantiation - delegates

class Program
{
delegate void StringProcessor(string input);
class Person
{
string name;
public Person(string name) { this.name = name; }
public void Say(string message)
{
Console.WriteLine("{0} says: {1}", name, message);
}
}
class Background
{
public static void Note(string note)
{
Console.WriteLine("({0})", note);
}
}
static void Main(string[] args)
{
Person jon = new Person("Jon");
Person tom = new Person("Tom");
StringProcessor jonsVoice, tomsVoice, background;
jonsVoice = new StringProcessor(jon.Say);
tomsVoice = new StringProcessor(tom.Say);
background = new StringProcessor(Background.Note);
StringProcessor p = new StringProcessor(jonsVoice);
p += tomsVoice;
p -= jonsVoice;
p("Hello");
}
}
This program prints
Jon says: Hello
Tom says: Hello
instead of
Tom says: Hello
This removal doesn't work: p -= jonsVoice;
But why?
Could you please clarify this or get some useful links about delegate instantiation with another delegate. I'm interested in undercover information.

A delegate is an object which represents a method and, optionally, the "this" object associated with that method.
When you combine delegates using the += operator, the result is a Multicast Delegate that represents a list of delegates to be invoked. (In fact all delegates are Multicast delegates, creating a delegate like this:
jonsVoice = new StringProcessor(jon.Say);
results in a Multicast Delegate with a single delegate in it's InvocationList).
You can remove delegates from the Invocation list by using the -= operator.
So why didn't your example above work? Because there is no delegate matching jonsVoice in the invocation list of p.
p has an invocation list that consists of two delegates:
one pointing at the Say method of the tomObject
one pointing at the Invoke method of a StringProcessor object
That is because you initialised p by passing the StringProcessor constructor another StringProcessor:
jonsVoice = new StringProcessor(jon.Say);
...
StringProcessor p = new StringProcessor(jonsVoice);
Resulting in a StringProcessor delegate that points at another StringProcessor delegate.
You can examine the invocation list of a delegate by calling the GetInvocationList method on that delegate. This will return an array of delegates in the order they would be invoked.
StringProcessor p = new StringProcessor(jonsVoice);
p += tomsVoice;
p -= jonsVoice;
foreach (var delegateItem in p.GetInvocationList())
{
Console.WriteLine("Delegate of {0}.{1}", delegateItem.Target.GetType().Name, delegateItem.Method.Name);
}
Which results in:
Delegate of StringProcessor.Invoke
Delegate of Person.Say
When you call p -= jonsVoice, the invocation list does not contain a delegate that points at the Person.Say method of the jon objects (like jonsVoice does) and so there is nothing to remove.
If you initialize p like this instead:
StringProcessor p = jonsVoice;
You should get the results you expect.

Related

why singleton design pattern allowing copy of object even copy constructor and assignment operator are private?

I have created below singleton class and defined copy constructor and assignment operator as a private. When I invoke copy constructor or assignment operator, it does not call copy constructor and assignment operator(Maybe due to statically object creation). So my question is why singleton design pattern allows creating copy of object or assigning new object(which violates basic requirement of creating single instantiation of a class) form previously created object even they are declared private in a class?
Consider below code for details:-
#include <iostream>
#include "conio.h"
class singleton
{
static singleton *s;
int i;
singleton()
{
};
singleton(int x):i(x)
{ cout<<"\n Calling one argument constructor";
};
singleton(const singleton&)
{
cout<<"\n Private copy constructor";
}
singleton &operator=(singleton&)
{
cout<<"\n Private Assignment Operator";
}
public:
static singleton *getInstance()
{
if(!s)
{
cout<<"\n New Object Created\n ";
s=new singleton();
return s;
}
else
{
cout<<"\n Using Old Object \n ";
return s;
}
}
int getValue()
{
cout<<"i = "<<i<<"\n";
return i;
}
int setValue(int n)
{
i=n;
}
};
singleton* singleton::s=0;
int main()
{
// Creating first object
singleton *s1= singleton::getInstance();
s1->getValue();
singleton *s4=s1; // Calling copy constructor-not invoking copy ctor
singleton *s5;
s5=s1; // calling assignment operator-not invoking assign ope
//Creating second object
singleton *s2=singleton::getInstance();
s2->setValue(32);
s2->getValue();
//Creating third object
singleton *s3=singleton::getInstance();
s3->setValue(42);
s3->getValue();
getch();
return 0;
}
Am I missing something or my understanding is wrong.
Please help in this.
Thanks in advance.
It is always the same object. You are using pointers to access that singleton here!
It is like having 3 egg boxes, but only one egg, that "over time" placed in the different boxes. That comparison isn't perfect, but hopefully close enough.

How to get element's (defined as TagHelper) content in TagHelper.Process?

How to get elements defined as TagHelper content?
E.g. element defined as:
<markdown>bla bla</markdown>
And helper defined as:
[HtmlTargetElement("markdown")]
public class MarkdownTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var c = output.Content.GetContent();
// c is empty; how to get content "bla bla"?
}
}
You can use output.GetChildContentAsync() as explained in the docs (worth reading as it contains a few examples that retrieve the element's contents).
You will then implement your tag helper as in:
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var c = (await output.GetChildContentAsync()).GetContent();
// transform markdown in c
}

Extension method with generic Func parameter of other type

Is there a way to implement an extension method to a generic type that takes in arguments a Func of another type?
For exemple, a usage something similar to this:
myFirstObject.Extension<myOtherObject>( other => other.Prop );
Or with a more complicated Func:
myFirstObject.Extension<myOtherObject>( other => other.Prop > 2 && other.Prop < 15 );
I found some related question like this one, but in my case, I need generic types inside the extension method too.
Here's what I came up with:
public static bool Extension<TSource, TIn, TKey>(this TSource p_Value, Expression<Func<TIn, TKey>> p_OutExpression)
{ return true; }
However, when I try to use it, it does not take into consideration the second type.
Am I missing something?
Look at this:
s => s.Length;
How's the compiler suppose to know whether or not s is a string or s is an array or some other type that has a Length property? It can't, unless you give it some information:
(string s) => s.Length;
Oh, there we go. So now, try this:
myFirstObject.Extension((myOtherObject o) => o.Prop > 2 && o.Prop < 15);
That will work, because you've told the compiler what it should use for TIn, and it can figure out what to use for TKey based on the expression.
I found that another solution would be to create another method that takes in argument a type.
For instance:
Void Extension(Type p_Type, [THE TYPE] p_Params)
{
MethodInfo realExtensionMethod = typeof([CLASS CONTAINING THE METHOD]).GetMethod("RealExtension");
realExtensionMethod = realExtensionMethod.MakeGenericMethod(p_Type);
realExtensionMethod.Invoke(null, new object[] {p_Type, p_Params });
}
Void RealExtension<TYPE>(params)
{
}
Then at usage time:
Type objectType = typeof(myOtherObject);
myFirstObject.Extension(objectType, other => other.Prop );
When you call a generic method in C# you can explicitly declare all of the generic type parameters or you can have them all inferred, but you cannot have some explicitly declared and some inferred.
So, if I had this method:
public void Foo<X, Y>(X x, Y y)
{
/* Do somethhing */
}
Then here's what works and what doesn't:
int a = 42;
string b = "Hello, World!";
// Legal
Foo(a, b);
Foo<int, string>(a, b);
//Illegal
Foo<int>(a, b);
The best you can do is move the first generic parameter up to the class level, but not it won't work as an extension method. Nevertheless you may like this approach.
public static class Class<TSource>
{
public static bool Method<TIn, TKey>(
TSource p_Value,
Expression<Func<TIn, TKey>> p_OutExpression)
{
return true;
}
}
Now you can call it like this:
Expression<Func<long, decimal>> f =
l => (decimal)l;
var result = Class<int>.Method(a, f);
But as I say, it won't work as an extension method now.

Is it possible to create an IObservable from an Action listener?

I have a class that has an event defined as an Action<Guid>, as opposed to a classic EventHandler with EventArgs. Is there a way to convert this to an IObservable the same way would be done with a standard EventHandler? I need to do this so I can merge with other IObservables.
If you have this class:
public class Foo
{
public event Action<Guid> Guid;
}
Then this is the code you need to turn the non-standard event into an IObservable<Guid>:
var foo = new Foo();
var guids = Observable.FromEvent<Guid>(
h => foo.Guid += h,
h => foo.Guid -= h);

differences between bound and unbound delegates in CLI/C++

Whats the difference between bound and unbound delegates?
heres how you create delegates of both types:
// bound delegate declaration
public delegate void Handler(int value);
// create a bound delegate
Handler^ handler = gcnew Handler(HandlerClass::Fun1);
// unbound delegate declaration
public delegate void UBHandler(ThisClass^, int value);
// create an unbound delegate
UBHandler^ ubh = gcnew UBHandler(&ThisClass::Sum);
these are nearly the same. then, you can create constructors for bound delegates that consist of two parameters:
HandlerClass^ obj = gcnew HandlerClass;
Handler^ handler2 = gcnew Handler (obj, & HandlerClass::Fun3);
it means that you can use this particular delegate to invoke a function that is not static (is an instance). but then you can do the same with unbound delegates. Here’s how you might call the ubh delegate:
ThisClass^ obj = gcnew ThisClass(99.0);
ubh(obj, 5);
so whats the point of having both types?
// code for HandlerClass
public ref class HandlerClass
{
public:
static void Fun1(int m)
{ Console::WriteLine(L”Function1 called with value {0}”, m); }
static void Fun2(int m)
{ Console::WriteLine(L”Function2 called with value {0}”, m); }
void Fun3(int m)
{ Console::WriteLine(L”Function3 called with value {0}”, m+value); }
void Fun4(int m)
{ Console::WriteLine(L”Function4 called with value {0}”, m+value); }
HandlerClass():value(1){}
HandlerClass(int m):value(m){}
protected:
int value;
};
The difference is the exact time the target object value is generated. With a bound delegate it is generated when you create the delegate object and it is forever unchanging after that. An unbound delegate doesn't store the object reference, it is generated at the time the delegate is invoked. The same delegate can then be used to invoke the target method with different objects.
Unbound delegates are a match with the syntax of C++ member function pointers. There is no direct equivalent for bound delegates in C++.

Resources