Search Results

Search found 577 results on 24 pages for 'delegates'.

Page 10/24 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How do you pass a generic delegate argument to a method in .NET 2.0

    - by Seth Spearman
    Hello, I have a class with a delegate declaration as follows... Public Class MyClass Public Delegate Function Getter(Of TResult)() As TResult 'the following code works. Public Shared Sub MyMethod(ByVal g As Getter(Of Boolean)) 'do stuff End Sub End Class However, I do not want to explicitly type the Getter delegate in the Method call. Why can I not declare the parameter as follows... ... (ByVal g As Getter(Of TResult)) Is there a way to do it? My end goal was to be able to set a delegate for property setters and getters in the called class. But my reading indicates you can't do that. So I put setter and getter methods in that class and then I want the calling class to set the delegate argument and then invoke. Is there a best practice for doing this. I realize in the above example that I can set set the delegate variable from the calling class...but I am trying to create a singleton with tight encapsulation. For the record, I can't use any of the new delegate types declared in .net35. Answers in C# are welcome. Any thoughts? Seth

    Read the article

  • How to properly dispose of an object

    - by VoodooChild
    Hi Guys, 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(); } So 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; }

    Read the article

  • Get parent page values from the usercontrol

    - by Nimesh
    How to get the parent page values from the usercontrol. I have a usercontrol in a page. On click of the usercontrols button i wanna get some values from the page after executing a method. i need those values in my usercontrol. What is the best way to get the results of the page in the usercontrol.

    Read the article

  • How to avoid raising an event to a closed form?

    - by Steve Dignan
    I'm having trouble handling the scenario whereby an event is being raised to a closed form and was hoping to get some help. Scenario (see below code for reference): Form1 opens Form2 Form1 subscribes to an event on Form2 (let's call the event FormAction) Form1 is closed and Form2 remains open Form2 raises the FormAction event In Form1.form2_FormAction, why does this return a reference to Form1 but button1.Parent returns null? Shouldn't they both return the same reference? If we were to omit step 3, both this and button1.Parent return the same reference. Here's the code I'm using... Form1: public partial class Form1 : Form { public Form1 () { InitializeComponent(); } private void button1_Click ( object sender , EventArgs e ) { // Create instance of Form2 and subscribe to the FormAction event var form2 = new Form2(); form2.FormAction += form2_FormAction; form2.Show(); } private void form2_FormAction ( object o ) { // Always returns reference to Form1 var form = this; // If Form1 is open, button1.Parent is equal to form/this // If Form1 is closed, button1.Parent is null var parent = button1.Parent; } } Form2: public partial class Form2 : Form { public Form2 () { InitializeComponent(); } public delegate void FormActionHandler ( object o ); public event FormActionHandler FormAction = delegate { }; private void button1_Click ( object sender , EventArgs e ) { FormAction( "Button clicked." ); } } Ideally, I would like to avoid raising events to closed/disposed forms (which I'm not sure is possible) or find a clean way of handling this in the caller (in this case, Form1). Any help is appreciated.

    Read the article

  • Creating and releasing objects in the same method, while using self as delegate

    - by user200341
    In objective-c you are responsible for releasing objects you allocate, but what happens when you allocate an object in a method, assign self as the objects delegate, and then release the object. The callbacks from the newly created (and released) object fails at this point, or rather, doesn't happen. - (void)doSomething { MyObj *myObj = [[MyObj alloc] init]; myObj.delegate = self; [myObj performOperation]; [myObj release]; } - (void)callbackMethodFromMyObj:(NSString *)message { NSLog(message); } I can't release the object until the callback has occurred, and I can't avoid releasing the object in the same method that creates it (because it exists outside the scope). One way of doing it would be to pass the object along in the call-back and release it in the callback, but is this the right way to go about this?

    Read the article

  • C# specifying generic delegate type param at runtime

    - by smerlin
    following setup, i have several generic functions, and i need to choose the type and the function identified by two strings at runtime. my first try looked like this: public static class FOOBAR { public delegate void MyDelegateType(int param); public static void foo<T>(int param){...} public static void bar<T>(int param){...} public static void someMethod(string methodstr, string typestr) { MyDelegateType mydel; Type mytype; switch(typestr) { case "int": mytype = typeof(int); break; case "double": mytype = typeof(double); break; default: throw new InvalidTypeException(typestr); } switch(methodstr) { case "foo": mydel = foo<mytype>; //error break; case "bar": mydel = bar<mytype>; //error break; default: throw new InvalidTypeException(methodstr); } for(int i=0; i<1000; ++i) mydel(i); } } since this didnt work, i nested those switchs (a methodstr switch inside the typestr switch or viceversa), but that solution is really ugly and unmaintainable. The number of types is pretty much fixed, but the number of functions like foo or bar will increase by high numbers, so i dont want nested switchs. So how can i make this working without using nested switchs ?

    Read the article

  • Question About id and Delegate Usage in Obj-C

    - by Stunner
    Ey guys, I am wondering what the following line of code is doing: @property (assign, nonatomic) id <CoursePlannerDelegate> delegate; Namely I am wondering about this portion of the line: id <CoursePlannerDelegate> delegate; It also shows up in other places: @interface CategoryAddViewController : UIViewController { UITextField *nameField, *weightField; double maxWeight; //The maximum weight that can be allocated to this Category (max value of 100) id <CategoryAddDelegate> delegate; //A Course Planner TVC } Any help appreciated, thanks in advance!

    Read the article

  • What is the purpose of this delegate usage?

    - by Kev
    Whilst poking around some code in .NET Reflector in an app I don't have the source code for I found this: if (DeleteDisks) { using (List<XenRef<VDI>>.Enumerator enumerator3 = list.GetEnumerator()) { MethodInvoker invoker2 = null; XenRef<VDI> vdiRef; while (enumerator3.MoveNext()) { vdiRef = enumerator3.Current; if (invoker2 == null) { // // Why do this? // invoker2 = delegate { VDI.destroy(session, vdiRef.opaque_ref); }; } bestEffort(ref caught, invoker2); } } } if (caught != null) { throw caught; } private static void bestEffort(ref Exception caught, MethodInvoker func) { try { func(); } catch (Exception exception) { log.Error(exception, exception); if (caught == null) { caught = exception; } } } Why not call VDI.destroy() directly. Is this just a way of wrapping the same pattern of try { do something } catch { log error } if it's used a lot?

    Read the article

  • C# Property Delegate?

    - by Mark
    In my other methods I could do something like this, public void Add(T item) { if (dispatcher.CheckAccess()) { ... } else { dispatcher.Invoke(new Action<T>(Add), item); } } But how do I invoke a property for a situation like this? public T this[int index] { get { ... } set { if (dispatcher.CheckAccess()) { ... } else { dispatcher.Invoke(???, index); // <-- problem is here } } }

    Read the article

  • Create empty C# event handlers automatically

    - by TomA
    It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null. if ( MyEvent != null ) { MyEvent( param1, param2 ); } I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case. MyEvent( param1, param2 ); Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc. void Initialize() { MyEvent += new MyEvent( (p1,p2) => { } ); } Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?

    Read the article

  • Pass an event into a constructor

    - by Vaccano
    I have a class that I want to be able the handle the mouse up event for a grid. I tried to create it with a static method call like this: MyDataBinding.BindObjectsToDataGrid(ListOfObjectsToBind, myGrid.MouseUp); The end goal being that in the method I would assign a delegate to the MouseUp PassedInMouseUp += myMethodThatWillHandleTheMouseUp; Looks good here (to me) but the compiler chokes on the first line. It says that I can only use MouseUp with a += or a -=. Clearly I am going about this the wrong way. How can I get a different class to handle the mouse up with out having to: Pass in the whole grid Expose the method that will be handling the mouse up as a public method. Or, is this just a limitation and I will have to do one of the above?

    Read the article

  • Translating a C# WCF app into Visual Basic

    - by MikeG
    I'm trying to write a simple/small Windows Communication Foundation service application in Visual Basic (but I am very novice in VB) and all the good examples I've found on the net are written in C#. So far I've gotten my WCF service application working but now I'm trying to add callback functionality and the program has gotten more complicated. In the C# example code I understand how everything works but I am having trouble translating into VB the portion of code that uses a delegate. Can someone please show the VB equivalent? Here is the C# code sample I'm using for reference: namespace WCFCallbacks { using System; using System.ServiceModel; [ServiceContract(CallbackContract = typeof(IMessageCallback))] public interface IMessage { [OperationContract] void AddMessage(string message); [OperationContract] bool Subscribe(); [OperationContract] bool Unsubscribe(); } interface IMessageCallback { [OperationContract(IsOneWay = true)] void OnMessageAdded(string message, DateTime timestamp); } } namespace WCFCallbacks { using System; using System.Collections.Generic; using System.ServiceModel; public class MessageService : IMessage { private static readonly List<IMessageCallback> subscribers = new List<IMessageCallback>(); //The code in this AddMessage method is what I'd like to see re-written in VB... public void AddMessage(string message) { subscribers.ForEach(delegate(IMessageCallback callback) { if (((ICommunicationObject)callback).State == CommunicationState.Opened) { callback.OnMessageAdded(message, DateTime.Now); } else { subscribers.Remove(callback); } }); } public bool Subscribe() { try { IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>(); if (!subscribers.Contains(callback)) subscribers.Add(callback); return true; } catch { return false; } } public bool Unsubscribe() { try { IMessageCallback callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>(); if (!subscribers.Contains(callback)) subscribers.Remove(callback); return true; } catch { return false; } } } } I was thinking I could do something like this but I don't know how to pass the message string from AddMessage to DoSomething... Dim subscribers As New List(Of IMessageCallback) Public Sub AddMessage(ByVal message As String) Implements IMessage.AddMessage Dim action As Action(Of IMessageCallback) action = AddressOf DoSomething subscribers.ForEach(action) 'Or this instead of the above three lines: 'subscribers.ForEach(AddressOf DoSomething) End Sub Public Sub DoSomething(ByVal callback As IMessageCallback) 'I am also confused by: '((ICommunicationObject)callback).State 'Is that casting the callback object as type ICommunicationObject? 'How is that done in VB? End Sub

    Read the article

  • passing Func<TSource, TKey> keySelector error

    - by user338429
    static void Main() { string[] a = { "a", "asd", "bdfsd", "we" }; a = a.OrderBy(fun).ToArray(); } private static int fun(string s) { return s.Length; } its is giving compile time error . I know that we can do this with Lambda expression like this. a.OrderBy(s=>s.Length).ToArray(); but i want to this do by defining different function . What mistake i have done?

    Read the article

  • Generic delegate instances

    - by Luc C
    I wonder if C# (or the underlying .NET framework) supports some kind of "generic delegate instances": that is a delegate instance that still has an unresolved type parameter, to be resolved at the time the delegate is invoked (not at the time the delegate is created). I suspect this isn't possible, but I'm asking it anyway... Here is an example of what I'd like to do, with some "???" inserted in places where the C# syntax seems to be unavailable for what I want. (Obviously this code doesn't compile) class Foo { public T Factory<T>(string name) { // implementation omitted } } class Test { public void TestMethod() { Foo foo = new Foo(); ??? magic = foo.Factory; // No type argument given here yet to Factory! // What would the '???' be here (other than 'var' :) )? string aString = magic<string>("name 1"); // type provided on call int anInt = magic<int>("name 2"); // another type provided on another call // Note the underlying calls work perfectly fine, these work, but i'd like to expose // the generic method as a delegate. string aString2 = foo.Factory<string>("name 1"); int anInt2 = foo.Factory<int>("name 2"); } } Is there a way to actually do something like this in C#? If not, is that a limitation in the language, or is it in the .NET framework?

    Read the article

  • (Action<T>).Name does not return expected values

    - by Tomas Lycken
    I have the following method (used to generate friendly error messages in unit tests): protected string MethodName<TTestedType>(Action<TTestedType> call) { return string.Format("{0}.{1}", typeof(TTestedType).FullName, call.Method.Name); } But when I call it as follows, I don't get the expected results: var nm = MethodName<MyController>(ctrl => ctrl.Create()); After running this code, nm contains "<Create_CreateShowsView>b__8", and not (as expected) "Create". How should I change the code to obtain the expected result?

    Read the article

  • how to call async method until get success response?

    - by ppp
    I am making a async method call through a delegate. Delegate pointing to a function is a void function. How can I know that the async function has been executed successfully and if not the again call that function untill I get success response. here my code- BillService bs = new BillService(); PayAdminCommisionDelegate payCom = new PayAdminCommisionDelegate(bs.PaySiteAdminByOrderNo); payCom.BeginInvoke(OrderNo,null,null);

    Read the article

  • C# Events between threads executed in their own thread (How to) ?

    - by Guillaume
    Hello, I'd like to have two Threads. Let's call them : Thread A Thread B Thread A fires an event and thread B listen to this event. When the Thread B Event Listener is executed, it's executed with the Thread A's thread ID, so i guess it is executed within the Thread A. What I'd like to do is be able to fire event to Thread B saying something like: "hey, a data is ready for you, you can deal with it now". This event must be executed in its own Thread because it uses things that only him can access (like UI controls). How can I do that ? Thank you for you help.

    Read the article

  • Why delegate types are derived from MulticastDelegate class why not it directly derive from Delegate class?

    - by Vijay
    I have a very basic question regarding delegate types. I compared the memebers of Delegate and MulticastDelegate classes in object browser and I couldn't find any new additional member present in MulticastDelegate. I also noticed that the Delegate class has GetInvocationList virtual method. So I assume that the Delegate class should have the capability to hold references to multiple methods. If my assumption is correct I wonder why not custom delegate types directly derive from the Delegate class instead of MulticastDelegate class. Not sure what I am missing here. Please help me understand the difference.

    Read the article

  • Delegate Method only Firing after 5 or so Button Presses?

    - by CoDEFRo
    I'm having the most bizarre problem which I'm not even close to figuring out. I have a button which fires a delegate method. Once upon a time it was working fine, but after making some changes to my code, now the delegate method only fires after I push the button x amount of times (the changes I made to the code had nothing to do with the infrastructure that connects the delegate together). It varies, it can be 5 times to 10 times. I used the analyzer to check for memory leaks and there aren't any. There is too much code for me to paste here (I don't even know where to start or where the problem could be), but I'm wondering if anyone has experienced this problem before, or what could be causing it? This is very odd and have no clue what could be causing it.

    Read the article

  • "Method name expected" error when trying add a handler method to a delegate - C#

    - by zakplayyy
    I keep getting the error "Method name expected" when trying add the a method to a delegate. I have a delegate which is invoked when ever my game ends. The function I'm trying to add to the delegate stops a countdown from flashing (the method is in a static class). I've searched about and I'm still unsure why its not working. Here is the line causing the error: LivesManager.gameEnded += new LivesManager.EndGame(CountdownManager.DisableFlashTimer(this)); The this passes the current form to the method so it can disable the timer flash on the form. I have added methods from static classes to the same delegate before and it works fine, the only difference is that I'm passing the form as a paramater and then it doesn't like it. Is there any way to pass the form to the method without the error? Thanks in advance :)

    Read the article

  • iOS: Releasing Object Thats In Use (ARC)

    - by RileyE
    I have an object that I have created that subscribes to some NSNotificationCenter notifications, but it is being released, since I don't have a pointer to the instantiation. The instantiation has a delegate that will call a method back to another class I have, so I felt it unnecessary to also have a pointer to it, since the pointer doesn't serve any purpose. Basically, I have an instantiation of a class, DelegateListener (name is just for example purposes), which subscribes to some of the default NSNotificationCeneter's notifications. This instantiation isn't assigned to any pointer after the instantiation ends. The instantiation, however, has a property, delegate. I assign a value to that delegate during the instantiation. That delegate implements methods that I want the DelegateListener to call when the notifications that it subscribed to fire. The problem with this is that the instantiation of DelegateListener that I create gets released, unless if I assign it to a retained pointer. Is there a way to avoid this automatic release of my DelegateListener instantiation within ARC?

    Read the article

  • what exactly is delegate in C#

    - by Learning.net
    Hi All, can somebody explain the use of delegate..I know that it is used to invoke methods at run time...but exactly what does it mean..can somebody explain it with some simple example, which will help a newcomer to understand delegate better

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >