Ron and Ella Wiki Page

Extremely Serious

Page 18 of 33

Extension Methods

The method that allows to add methods to existing type without creating a new derived type, recompiling, or otherwise modifying the original type.

A method signature template with a return value and an argument

public static <T_RETURN> <METHOD_NAME>(this <T_TYPE> <VAR_NAME>, <T_ARG1_TYPE> <ARG1_NAME>)
Token Description
T_RETURN The type of the return value.
METHOD_NAME The desired name of the method.
T_TYPE The existing type to extend.
VAR_NAME The holder of an instance of the T_TYPE
T_ARG1_TYPE Type of the first argument.
ARG1_NAME The name of the first argument.

This method is actually a static method but the first argument has the keyword this and the target type to extend. Also it holds the instance of the target type.

The T_RETURN and the argument part of the template are optional. Also the argument is not limited to just one, you can have as many as required by your extension.

Class Property

Description

A member of a class that provides flexibility for exposing private fields.

Sample Property Declaration

//backing private field
private string prop;

public string ReadWriteProp {
    get {
        return prop;
    }
    set {
        prop = value;
    }
}

public string ReadOnlyProp {
    get {
        return prop;
    }
}

public string WriteOnlyProp {
    set {
        prop = value;
    }
}

Sample Auto-Implemented Property Declaration

A more concise property declaration especially if theres no additional logic required for the accessors.

public string ReadWriteProp {
    get; set;
} 

public string ReadOnlyProp {
    get; private set;
} 

public string WriteOnlyProp {
    private get; set;
}

The Delegate Type

Definition

Delegate is a type that references methods with a particular parameter list and return type.

Printer Custom Delegate

public delegate void Printer<T>(T data);

A Method for Printer Delegate

static void ConsoleWrite<T>(T data) {
    Console.WriteLine(data);
}

Reference the ConsoleWrite method with Printer delegate

Printer<String> consoleOut = new Printer<String>(ConsoleWrite);
consoleOut("test");

 

The virtual keyword

Usage

The virtual keyword allows to modify a method, property, indexer or event declaration and to be overridden in a derived class.

Example

public virtual double volume() {
   return len * width * height
}

Covariant vs Contravariant

Covariant

The type can vary in the direction as the subclass.

Contravariant

The reverse of covariant.

Example in Generics

Language Covariant Contravariant
C# IList<out T> IList<in T>
Java List<? extends Number> List<? super Integer>

C# Generic Delegates

Description

These are delegates built-in with the framework and ready for your use.

List of Generic Delegates

Delegate NameArgumentsReturnsComment
Actionvoid
Action<T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16>(T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16)voidThis version of Action delegate can have 1 up to 16 arguments of different types.
Func<TResult>TResult
Func<T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16,TResult>(T1,T2,T3,T4, T5,T6,T7,T8, T9,T10,T11,T12, T13,T14,T15,T16)TResultThis version of Func delegate can have 1 up to 16 arguments of different types.
Predicate<T>Tbool

Common Table Expression (CTE) – With Clause

The with clause is also known as common table expression (CTE) and subquery refactory. It is a temporary named result set.

SQL:1999 added the with clause to define "statement scoped views". They are not stored in the database scheme: instead, they are only valid in the query they belong to. This makes it possible to improve the structure of a statement without polluting the global namespace.

Syntax

with <QUERY_NAME_1> (<COLUMN_1>[, <COLUMN_2>][, <COLUMN_N>]) as
     (<INNER_SELECT_STATEMENT>)
[,<QUERY_NAME_2> (<COLUMN_1>[, <COLUMN_2>][, <COLUMN_N>]) as
     (<INNER_SELECT_STATEMENT>)]
<SELECT_STATEMENT>

Non-Recursive Example

with sales_tbl as (
select sales.*
	from (VALUES
		('Spiderman',1,19750),
		('Batman',1,19746),
		('Superman',1,9227),
		('Iron Man',1,9227),
		('Wonder Woman',2,16243),
		('Kikkoman',2,17233),
		('Cat Woman',2,8308),
		('Ant Man',3,19427),
		('Aquaman',3,16369),
		('Iceman',3,9309)
	) sales (emp_name,dealer_id,sales)
)
select ROW_NUMBER() over (order by dealer_id) as rownumber, *
from sales_tbl

Recursive Example

WITH [counter] AS (

   SELECT 1 AS n  -- Executes first and only once.

   UNION ALL      -- UNION ALL must be used.

   SELECT n + 1   -- The portion that will be executed 
   FROM [counter] -- repeatedly until there's no row 
                  -- to return.

   WHERE  n < 50  -- Ensures that the query stops.
)
SELECT n FROM [counter]

SQL Window Functions

Window functions are closely related to aggregate functions except that it retains all the rows.

Categories

Aggregate Window Functions

Ranking Window Functions

Value Window Functions

Example

with sales_tbl as (
select sales.*
	from (VALUES
		('Spiderman',1,19750),
		('Batman',1,19746),
		('Superman',1,9227),
		('Iron Man',1,9227),
		('Wonder Woman',2,16243),
		('Kikkoman',2,17233),
		('Cat Woman',2,8308),
		('Ant Man',3,19427),
		('Aquaman',3,16369),
		('Iceman',3,9309)
	) sales (emp_name,dealer_id,sales)
)
select ROW_NUMBER() over (order by dealer_id) as rownumber,
	*,
	AVG(sales) over (partition by dealer_id) as [Average Sales by DealerID],
	SUM(sales) over (partition by dealer_id) as [Total Sales by DealerID],
	SUM(sales) over (partition by dealer_id order by sales rows between unbounded preceding and current row) as [Running Total by DealerID]
from sales_tbl

Value Window Functions

LAG()

Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.

LEAD()

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Common Syntax

LAG | LEAD
( expression )
OVER ( [ PARTITION BY expr_list ] [ ORDER BY order_list ] )

FIRST_VALUE()

Returns the first value in an ordered set of values in SQL Server 2019

LAST_VALUE()

Returns the last value in an ordered set of values in SQL Server 2019 (15.x).

Common Syntax

FIRST_VALUE | LAST_VALUE
( expression ) OVER
( [ PARTITION BY expr_list ] [ ORDER BY order_list ][ frame_clause ] )
« Older posts Newer posts »