Delegates/Arrays Flashcards

1
Q

Delegates

A

“Delegate type” is a “type” that represents methods that have specific parameters and return type.

The “delegate” (a.k.a. delegate object), is an object that stores reference (address) of a specific method of a specific class, with compatible parameters and return type, which is already defined in the delegate type.

  1. Creating Delegate Type

public delegate ReturnType DelegateTypeName(param1, param2);

  1. Creating Delegate Object

DelegateTypeName ReferenceVariable = new DelegateTypeName(MethodName);

  1. Invoke Method using Delegate Object

ReferenceVariable.Invoke(arg1, arg2, …);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Rules of Delegates

A

You can invoke the methods using ‘delegate objects’ (or) ‘delegates’.

Delegates are used to pass methods as arguments to other methods.

The method signature (parameters and return type) must match between the “method” and “delegate”.

Delegates can be used as “parameter type” or “return type” of a method.

You can store references of non-static method or static method in the delegate object.

The methods, which reference is stored in the “single-cast delegate object”, can have return value.

The methods, which reference is stored in the “multi-cast delegate object”, can’t have return value; in case, if they have return value, the return value of lastly-executed method only can be received; others will be ignored.

All delegate types are derived from “System.Delegate” class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Types of Delegates

A

Single-Cast Delegates

Contains reference of only one method.

When called, it directly invokes the referenced method.

Multi-Cast Delegates

Contains references of multiple methods.

When called, it invokes all the referenced methods, one-by-one in a sequence.

All methods’ parameters and return type should be same.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Events

A

Event is a multi-cast delegate that stores one or more methods; and invoke them every time when the event is raised (called).

The event can be raised only in the same class, in which it is created.

Publisher class is a class that sends (or raises) events (notifications), is called as “publisher class”.

Publisher class sends events; then Subscriber class receives events.

Subscriber class is a class that receives (or subscribes or handles) events (notifications), is called as “subscriber class”.

Events enable a class to send notifications to other classes, when something occurs.

Publisher class sends events; Subscriber class receives events.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Process of Events

A

The Publisher class creates an event.

The Subscriber class subscribes to the event; that means an “event handler” method is created in the subscriber class. The “event handler” method is nothing but, the method which is dedicated to be executed when the event is raised.

The publisher class can send (raise) events.

Every time, when the event is raised by the publisher, the corresponding “event handler” method executes automatically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Rules of Events

A

The event should be created based on the delegate. That means, the event accepts the methods that are having specific parameters and return type, defined in the delegate.

An event can have multiple subscribers.

A subscriber can subscribe multiple events from multiple publishers.

Events are basically signals to inform to other classes, that some important thing happened in the publisher class.

Events are special kind of “multi-cast delegates”, which can be raised only within the same class, in which they are created.

Events can be static, virtual, sealed and abstract.

Events will not be raised (throws exception), if there is no at least one subscriber.

Events can be defined in interfaces.

It’s not a good idea to return value in events.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Auto-Implemented Events

A

“Auto-Implemented Events” provide a shortcut syntax to create events with less code.

In this case, you need not create “add” and “remove” accessors; the compiler does the same automatically.

You also not required to create a private multi-cast delegate; the compiler does the same automatically.

Disadvantage / Limitation: We can’t define custom logic for “add accessor” and “remove accessor”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Anonymous Methods

A

Anonymous methods are “name-less methods”, that can be invoked by using the delegate variable or an event.

Subscribe to Event with Anonymous Method:

EventName += delegate(param1, param2, …)
{
//method body here
}

Anonymous methods can be used anywhere within the method, to create methods instantly, without define a method at the class level.

Advantage: We need not create a “named method (normal method)” to quickly handle an event.

Rules:

It can’t be called without a delegate or event.

It can’t contain jump statements like goto, break, continue.

It can access local variables and parameters of outer method.

It can be passed as a parameter to any method; in this case, the delegate acts as data type for the anonymous method.

It can’t access ref or out parameter of an outer method.

It is mainly used for event handlers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Lambda Expressions

A

“Lambda Expressions” (a.k.a. Statement Lambda) are “name-less methods”, that can be invoked by using the delegate variable or an event, much like anonymous methods.

Handle Event with Lambda Expressions:

EventName += (param1, param2, …) =>
{
//method body here
}

Lambda Expressions can be used anywhere within the method, to create methods instantly, without define a method at the class level.

Advantage: It provides more easier and convenient syntax than “Anonymous methods”.

=> operator is called as “goes to” or “goes into” operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Inline Lambda Expressions

A

“Inline Lambda Expressions” (a.k.a. Expression Lambda) are the lambda expressions, which performs a small calculation or condition check and returns a value.

Inline lambdas can receive one or more arguments and must return a value.

Advantage: It provides more easier and convenient syntax to create smaller methods that performs a single calculation or condition check.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Expression Bodied Members

A

“Expression Bodied Members” concept allows the developer to use “Inline Lambda Expressions” to create methods, property accessors, constructors, destructors, indexers in a class.

Expression Bodied Members may have or parameters; may / may not have return value.

Expression Bodied Members can have only one statement.

Advantage: It provides more easier and convenient syntax to create smaller methods that performs a single calculation or condition check.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Switch Expression

A

The variable used in switch expression is now coming before the switch keyword.

Colon (:) and case keyword are replaced with arrows (=>). Which makes the code more compact and readable.

The default case is now replaced with a discard(_).

And the body of the switch is expression, not a statement.

‘Switch Expression’ returns the result value based on the matching case.

It is only meant for getting a specific result value; doesn’t let you to write multiple statements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Func

A

“Func” is a pre-defined generic-delegate, which can be used to create events quickly.

Func supports parameters and return value also.

  • Func must have 0 to 16 parameters.
  • Func must have return value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Action

A

“Action” is a pre-defined delegate, which can be used to create events quickly, similar to “Func”.

The difference is:

  1. Func must have return value; Action don’t have return value.
  2. Action must have 0 to 16 parameters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Predicate

A

“Predicate” is a pre-defined delegate, which can be used to create events quickly, similar to “Func”.

The difference is:

  1. Func must have return value of any type; Action don’t have return value; Predicate must have return value of “bool” type.
  2. Func can have 0 to 16 parameters of any type; Action can have 0 to 16 parameters of any type; Predicate must have only one parameter of any type.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

EventHandler

A

‘EventHandler’ is a pre-defined delegate type, which has two parameters called “object sender” and “EventArgs e”; and no return.

object sender: Represents the source object, where the from where the event is originally raised.

EventArgs e: Represents additional parameters to pass to ‘event handler method’. It is recommended to create a child class for ‘EventArgs’ class.

17
Q

Expression Trees

A

Expression Tree is a collection of delegates represented in tree-like structure.

Expression Tree only executes when we compile and execute it.

Expression Trees support all delegate types such as Func, Action, Predicate or custom delegate types.

18
Q

Properties of ‘System.Array’ class

A

Length

19
Q

Methods of ‘System.Array’ class

A

IndexOf

BinarySearch

Clear

Resize

Sort

Reverse

CopyTo

Clone

20
Q

Jagged Arrays

A

Jagged Array is an “array of arrays”.

The member arrays can be of any size.

21
Q

Array - CopyTo( ) method

A

This method copies ** (shallow copy) ** all the elements from source array to destination array, starting from the specified ‘startIndex’.

22
Q

CopieTo() vs Clone()

A

Array.CopyTo()

CopyTo() equires to have an existing destination array; and the destination array should be large enough to hold all elements from the source array, starting from the specified startIndex.

CopyTo() allows you to specify the startIndex at destination array.

The result array need not be type-casted explicitly.

Array.Clone()

Clone() creates a new destination array; you need not have an existing array.

Clone() doesn’t allow you to specify the startIndex at destination array.

The result array will be returned as ‘object’ type; so need to be type-casted to array type.

23
Q

Anonymous Types

A

When you create an object with a set of properties along with values; automatically C# compiler creates a class (with a random name) with specified properties. It is called as ‘anonymous type’ or ‘anonymous classes’.

Useful when you want to quickly create a class that contains a specific set of properties.

var person = new 
    {
        Name = "Alice",
        Age = 30,
        IsEmployed = true
    }
24
Q

Creating Anonymous Object (based on anonymous type)

A

var referenceVariable = new { Property1 = value, Property2 = value, … };

anonymous type [automatically generated]

class RandomClassName
{
public type Property1 { get; set; }
public type Property2 { get; set; }
}

Anonymous types are created by the C# compiler automatically at compilation time.

The data types of properties of anonymous types will be automatically taken based on the value assigned into the property.

Anonymous types are derived from System.Object class directly.

Anonymous types are by default sealed class.

Properties of anonymous types are by default readonly properties.

Anonymous types can’t contain other members such as normal properties, events, methods, fields etc.

Properties of anonymous types will be always ‘public’ and ‘readonly’.

You can’t add additional members of anonymous types once after compiler creates it automatically.

‘null’ can’t be assigned into property of anonymous type.

The data type of anonymous objects are always given as “var”.

Anonymous types can’t casted to any other type, except into System.Object type.

You can’t create a field, property, event or return type of a method, parameter type as of anonymous type.

It is recommended to use the anonymous objects within the same method, in which they are created. You can pass anonymous type object to method as parameter as ‘System.Object’ type; but it’s not recommended.

25
Q

Anonymous Arrays

A

You can create ‘array of anonymous objects’ or ‘implicitly typed array’ with group of anonymous objects.

All objects must contain same set of properties.

26
Q

Tuples

A

The System.Tuple class represents a set of values of any data type.

Introduced in C# 4.0.

Useful to return multiple values from a method (or) to pass multiple values to a method.

Represents a set of values quickly without creating a separate class.

Alternative to anonymous objects (to be used as parameter types / return types).

27
Q

What do Tuple store?

A

Tuple stores only a set of values (of any data type); but doesn’t store property names.

So you should access them as Item1, Item2 etc.; which doesn’t make sense some times.

var tuple1 = Tuple.Create(“John”, 30, “Engineer”);

Console.WriteLine($”Name: {tuple1.Item1}, Age: {tuple1.Item2}, Job: {tuple1.Item3}”);

Tuple supports up to 8 elements only by default. You can store more than 8 values by using nested tuples (tuple inside tuple).

Tuples are mainly used to pass multiple values to a method as parameter; and also return multiple values from a method.

its like JS Object:
// Tworzenie tuple:
var person = (Name: “John”, Age: 30);

// older version of tuples:
var person = new Tuple<string, int>(“John”, 30);

28
Q

Value Tuples

A

‘Value Tuples’ are advancement to ‘Tuple’ class with simplified syntax.

Introduced in C# 7.1.

Supports unlimited values.

You will access elements with real field names; instead of Item1, Item2 etc.

Can be used as method parameters / return value; much like Tuple class.

(string name, int age, string job) tuple2 = (“Alice”, 28, “Designer”);

    Console.WriteLine($"Name: {tuple2.name}, Age: {tuple2.age}, Job: {tuple2.job}");
29
Q

Deconstruction

A

Deconstruction allows you to assign elements of value tuple into individual local variables.

(type variableName1, type variableName2, …) = referenceVariable;

30
Q

Discards

A

Discard allows you to skip a value which you don’t require, by using underscore ( _ ).

Step 2: Deconstruction with Discard

(type variableName1, _ ) = referenceVariable;