Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
3. Delegates and events, reference pitfall
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//3. Delegates and events, reference pitfall using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { delegate bool TestPointer(int a); static event TestPointer SomeEvent; public static void Main(string[] args) { var some = new SomeClass(); SomeEvent += some.SomeMethod; SomeEvent(25); //It's important to realize that at this point SomeEvent is holding a reference to SomeClass instance some. //(Since it needs one to invoke it's method when fired.) //It's important to release this reference when no longer needed, if SomeEvent is going to live in memory long time. //Otherwise memory leaks may occur, since 'some' will live in memory just as long; SomeEvent -= some.SomeMethod; //Now 'some' can be garbage collected //SomeEvent(25); //SomeEvent == null since noone is subscribed } } public class SomeClass { byte[] HugeData; public bool SomeMethod(int a) { Console.WriteLine("From another class."); return true; } } }
Show compiler warnings
[
+
]
Show input
Compilation time: 0.12 sec, absolute running time: 0.11 sec, cpu time: 0.08 sec, average memory usage: 17 Mb, average nr of threads: 4
fork mode
|
history
|
discussion
From another class.