void Start() { // Initializing of delegate // <delegate-type> <name> = <name-of-method> DelegateExample myDelegate = Bar; myDelegate.Invoke(5); // Use another class Foobar(Foo); }
static void DelegeteInAction() { DelegateExample delExE1 = Hello; // reference DelegateExampleWithStr delExE2; // null delExE2 = null; // null delExE1.Invoke(); delExE2?.Invoke("Ping pong"); // nothing delExE2 = HelloUser; // reference delExE2?.Invoke("Batman"); // write in console "Hello, Batman" }
public void Activate_Code() { // Act DelegateExample example1 = Hello; DelegateExampleWithParam example2 = null; DelegateExample example3 = null; //DelegateExample example4 = HelloUser; not allowed operation // Action var example1Exception = Record.Exception(() => example1.Invoke()); var example2Exception = Record.Exception(() => example2?.Invoke("Ping pong")); // Assert Assert.Null(example1Exception); Assert.Null(example2Exception); Assert.Throws <NullReferenceException>(() => example3.Invoke()); }