C# Dynamic Event Subscription

You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler’s parameters to the events somehow. using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class ExampleEventArgs : EventArgs { public int IntArg {get; … Read more

Why can a .NET delegate not be declared static?

Try this: public delegate void MoveDelegate(object o); public static MoveDelegate MoveMethod; So the method-variable can be defined static. The keyword static has no meaning for the delegate definition, just like enum or const definitions. An example of how to assign the static method-field: public class A { public delegate void MoveDelegate(object o); public static MoveDelegate … Read more

Passing a Function (with parameters) as a parameter?

It sounds like you want a Func<T>: T GetCachedValue<T>(string key, Func<T> method) { T value; if(!cache.TryGetValue(key, out value)) { value = method(); cache[key] = value; } return value; } The caller can then wrap this in many ways; for simple functions: int i = GetCachedValue(“Foo”, GetNextValue); … int GetNextValue() {…} or where arguments are involved, … Read more

anonymous delegates in C#

Yes. In .NET 3.5 you can use Func and Action delegates. The Func delegates return a value, while Action delegates return void. Here is what the type names would look like: System.Func<TReturn> // (no arg, with return value) System.Func<T, TReturn> // (1 arg, with return value) System.Func<T1, T2, TReturn> // (2 arg, with return value) … Read more

Practical use of interface events [closed]

I used events to signal when a serial port received data. Here is my interface. public interface ISerialPortWatcher { event EventHandler<ReceivedDataEventArgs> ReceivedData; event EventHandler StartedListening; event EventHandler StoppedListening; SerialPortSettings PortOptions { set; } bool Listening { get; set; } void Stop(); void Start(); } public class ReceivedDataEventArgs : EventArgs { public ReceivedDataEventArgs(string data) { Data … Read more

In C#, why can’t I test if a event handler is null anywhere outside of the class that it’s defined?

An event is really just an “add” operation and a “remove” operation. You can’t get the value, you can’t set the value, you can’t call it – you can just subscribe a handler for the event (add) or unsubscribe one (remove). This is fine – it’s encapsulation, plain and simple. It’s up to the publisher … Read more

Inline delegate declaration (c#)

You don’t specify a return type when using anonymous methods. This would work: var x = new Action(delegate(){}); Some alternatives: Action x = () => {}; // Assuming C# 3 or higher Action x = delegate {}; Action x = delegate() {}; var x = (Action) (delegate{});

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)