fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,59 @@
---
title: Arrays
---
# Arrays
An array is used to store a collection of data of the same type. This can be used as a single variable that holds multiple values, or a collection of variables.
## Rules of Arrays
Arrays start from zero. The first element of an array is 0, the second element is 1, the third element 2, and so on.
Arrays must be of the same data type. You can use any data type in an array (e.g. int, double, float, string, enum)
A new Array must first be declared and initialised before it can be called and accessed.
## Declaring an Array
Use the following format for declaring arrays:
`dataType [] nameOfArray;`
## Initializing an array
Use the following format for initialising an array. This method also declares the array and states how many values are to be stored into the array.
`dataType [] nameOfArray = new nameOfArray[numberOfElements];`
## Assigning values to an array
You can assign a value into an element directly by using the format below:
`nameOfArray[2] = 50;`
The will assign the value of 50 directly into element [2]
You can assign multiple values at once while declaring the array using the format below:
`dataType [] nameOfArray = {5,17,19,92};`
The will assign the value of 5 into element [0], 17 into element [1], 19 into element [2] and 92 into element [3].
You can declare, initilise and assign values in the array all at once by using the format below:
`dataType [] nameOfArray = new nameOfArray[numberOfElements] {value1,value2,value3,value4};`
You can store an array directly into another array by using the format below:
`int [] nameOfArray = new nameOfArray[4] {2,9,56,1280};`
`int [] nameOfSecondArray = nameOfArray;`
## Advantages
* Can be easily accessed in a random manner
* Can be easily manipulated
## Disadvantages
* The only disadvantage is that the size of an array is fixed. (Hence, a list can be used in case of a dynamic sizing.)

View File

@ -0,0 +1,70 @@
---
title: Async / Await
---
# Async / Await Keywords
The `async`/`await` keywords in C# provide convenient ways of managing resource-intensive applications, which are more common in front-end languages such as Javascript libraries. Methods that return `Task<T>` types can be crowned with the `async` keyword, and when calling these methods in a UI handler or service workflow, we can use the `await` on the methods to tell C# to yield the control back to its caller until the background job is finished. By yielding the control on resources-intensive calls, we are able to allow UI to be more responsive and make the service more elastic.
The core of the `async` and `await` are the `Task<T>` class. When using it along with the `async` keyword as the return type of a method, we indicate that the method has promised to return an object of the `T` type (for methods that wouldn't return any value, use `Task` as the return type instead). `Task<T>` is a sophisticated topic of its own, for more information, please refer to the official documents: [Task Class](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=netframework-4.7.1).
Once encountering `async` methods, the work will be queued in a thread-pool for execution, while the caller will continue its execution without waiting on the return values from the `async` methods. However, in most occasions, our UI and service rely on the values returned from the `async` methods: for example, when we query a local database using the `async` methods, we would eventually want to know what are the query results and act on them, synchronously. This is where the `await` keyword shall be used: if using the `await` keyword when invoking an `async` method, the caller will pause the execution until a result is returned from the `async` method, and mean while, the parent method will continue execution without waiting on the caller to finish. With that said, any method that uses `await` keyword have to be an `async` function itself -- this is enforced by the C# compiler as well, if using Visual Studio to write your C# code, the IDE will warn you if a method violate the `async-await` contract.
To learn more about using the promise model to handle asynchrony, check out this wikipedia page: [Achieving Asynchrony through Promises](https://en.wikipedia.org/wiki/Futures_and_promises)
## Examples
1. Submit Form to the Server
```csharp
private readonly string url = "http://localhost:3000/api/submit";
private readonly HttpContent formContent = new HttpContent();
// Update the formContent object while filling up the form.
SubmitButton.Clicked += async (object, event) =>
{
// When PostAsync is hit, the button control will release the UI, while the
// http post method is still waiting on server response.
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, formContent);
Console.WriteLine(response.StatusCode);
}
```
2. "Latches" Synchronizer
```csharp
public async Task<int> CalcDamage(Player player)
{
// CPU-intense method, calculate afflicted damage done to the
// Boss based on the damage types, Boss stats (from static data),
// player stats, etc.
// ...
}
public static async Task<int> CalcTotalDamage(IEnumerable<Player> group)
{
var totalDamage = 0;
foreach (Player player in group)
{
// each of the async methods are queued in the thread-pool and move on.
totalDamage += CalcDamage(player);
}
// total damage done must be calculated from all players in the group
// before we return the result.
return await Task.WhenAll(totalDamage);
}
```
## Cheat-sheet
- await: retrieve the result from a background async call.
- await Task.WhenAny: continue if any of the queued tasks is complete.
- await Task.WhenAll: only continue if all of the queued tasks are complete.
- await Task.Delay: hold for an additional period of time before execution.
## In-depth read:
- [Asynchronous programming](https://docs.microsoft.com/en-us/dotnet/csharp/async)
- [Async in depth](https://docs.microsoft.com/en-us/dotnet/standard/async-in-depth)
- [3 essential tips for asnyc](https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async)

View File

@ -0,0 +1,66 @@
---
title: Break statement
---
# Break statement
The `break` statement terminates the enclosing loop or switch statement in which it appears. The control is passed to the statement that follows the loop or the switch block.
In the first example, when the value of i is 3, the break statement is executed, which causes the execution of the loop to be terminated.
## Example
```
int[] array = { 1, 2, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
if(i == 3)
{
break;
}
Console.WriteLine("Item on index {0} is {1}", i, array[i]);
}
```
## Output:
```
> Item on index 0 is 1
> Item on index 1 is 2
> Item on index 2 is 3
```
In the second example, a break statement is included at the end of each case. This executes the statements in the case without continuing to the next case. Without the break statement, the program would continue to execute the next case and would not function as intended.
## Example
```
switch (exampleVariable)
{
case 1:
Console.WriteLine("case 1");
Console.WriteLine("This only shows in example 1");
break;
case 2:
Console.WriteLine("case 2");
Console.WriteLine("This only shows in example 2");
Console.WriteLine("This also only shows in example 2");
break;
Console.WriteLine("This would not show anywhere, as it is after the break line and before the next case");
default:
Console.WriteLine("default");
Console.WriteLine("This only shows in the Default Example");
break;
}
```
## Output:
```
> case 1
> This only shows in example 1
>
> case 2
> This only shows in example 2
> This also only shows in example 2
>
> default
> This only shows in the Default Example
>
```

View File

@ -0,0 +1,71 @@
---
title: Class
---
## Class
A class in C# is defined as a reference type. In order to instatiate a variable of with a reference type you must specify the `new` keyword, else the variable will have the default value of `null`. See below for an example.
```csharp
// The value of variableOne is null at this point.
NewClass variableOne;
// Now the value of variableOne will be an instance of the class NewClass
variableOne = new NewClass();
```
At runtime when the class is created enough memory is allocated onto the heap for that specific instance of the class that the variable holds.
#### Creating Classes
To create a class in C# we need to use the `class` keyword followed by a unique identifier.
Like other languages, C# creates a default constructor that accepts no parameters. We can also specify our own constructor if we need to take in special parameters or have custom initlization steps in our constructor.
```csharp
public class NewClass
{
NewClass(string name)
{
// Initialization steps...
}
}
```
A class is a prototype or blueprint from which objects are created. In C#, the class is defined by using the keyword class. A class is used to combine together some methods, properties, fields, events, and delegates into a single unit. A class may contain nested classes too.
#### Example: Consider the case of Employee Class below:
```csharp
using System;
namespace CPrograms
{
class Employee
{
private string name;
private int employeeId;
public Employee(string name, int employeeId)
{
this.name = name;
this.employeeId = employeeId;
}
public void PrintEmployee()
{
Console.WriteLine("Employee Name: {0} , Employee ID: {1}", this.name, this.employeeId);
}
}
class Program
{
static void Main(string[] args)
{
Employee employeeObject = new Employee("John Doe", 420156);
employeeObject.PrintEmployee();
}
}
}
```
A class can inherit from one base class only. However, it can implement from more than one interface.
## More Information
Read more about classes [here](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/class)

View File

@ -0,0 +1,30 @@
---
title: Continue statement
---
# Continue statement
The `continue` statement passes control to the next iteration inside a loop.
In this example, when the value of i is 2, the next statement within the loop is skipped.
## Example
```
int[] array = { 1, 2, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
if( i == 2)
{
continue;
}
Console.WriteLine("Item on index {0} is {1}", i, array[i]);
}
```
## Output:
```
> Item on index 0 is 1
> Item on index 1 is 2
> Item on index 3 is 4
> Item on index 4 is 5
```

View File

@ -0,0 +1,63 @@
---
title: Delegates
---
## Delegates
A C# delegate represents a reference to a method that has a given set
of parameters and a given return type. When you instantiate the delegate, you can associate it with
any method that is compatible with the delegate type: has the same amount of parameters, each is of the
same type and the type of the return value is also the same.
You can either use an instance method or a static method when you assign it to a delegate.
Delegate allow you to pass methods as parameters to other methods.
Delegates are often used to implement callback functions. The most typical example are event handlers: you register
a method that is to be called whenever a certain event happens (the mouse button is clicked, for example).
### Short explanation for developers
Delegates are like function pointers in C type languages like C or C++. However, they are type safe.
Unlike simple function pointers they
contain information about the object instance whose method will be called when invoking the delegate, and have
strict type checks for the arguments and return value of the function.
## Example
You declare a delegate similar to how you declare a function, but add the `delegate` keyword. For example:
```csharp
public delegate string StringOperation ( string s1, string s2 );
```
Any method that takes two `string` arguments and returns `string` can be assigned to a variable of this delegate type.
After you have created the delegate type, you can use it just like any other type. You can declare a local variable,
other class members or pass them as parameters to other methods.
```csharp
StringOperation a;
```
Before invoking the delegate, you will need to assign a value to it. Let's assume we have a concatenation method
that has the following implementation:
```csharp
private string Concatenate ( string one, string two ) {
return one + " " + two;
}
```
You can then assign this to the delegate variable and invoke it like a function.
```csharp
StringOperation op = Concatenate;
string result = op("Hello", "World");
Console.WriteLine ( result ); // print "Hello World" to the console
```
## More information
Read more about delegates [here](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/).

View File

@ -0,0 +1,40 @@
---
title: Do while loop
---
# Do while Loop
The `do while` loop executes a block of code once and until a condition is false. They are a particular case of <a href='https://guide.freecodecamp.org/csharp/while-loop' target='_blank' rel='nofollow'>`while` loops</a>: they execute a block of code one time and then until the condition is false. A common use of `do while` loops are input checks.
## Example
```
do
{
//execute code block
} while(boolean expression);
string input = "";
do
{
Console.WriteLine("Type A to continue: ");
input = Console.ReadLine();
} while(input != "A");
Console.WriteLine("Bye!");
```
## Output:
```
> Type A to continue: b
> Type A to continue: g
> Type A to continue: A
> Bye!
```
#### More Information:
* [Microsoft C# - do](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do)
* [Dot Net Perls - do](https://www.dotnetperls.com/do)

View File

@ -0,0 +1,46 @@
---
title: Enumerations
---
# Enumerations
An enumeration is a set of named integer constants that is declared using the `enum` keyword.
## Example
```
enum Gender
{
Male,
Female
}
```
By default, the integer values start at 0 and increase by 1, for each enumeration name i.e. Male = 0, Female = 1 etc.
These can be overridden by specifying an integer value for any of the enumeration names.
## Example
```
enum Gender
{
Male = 1,
Female
}
```
In this case, the integer values will start at 1 and increase from there.
To use an enum, you can declare a variable of its type and assign a value to it:
`Gender myVar = Gender.Male;`
You can also cast an enumeration name value to it's underlying integer value and visa versa:
```
Console.WriteLine($"Male: {(int)Gender.Male}");
Console.WriteLine($"Female: {(int)Gender.Female}");
```
## Output:
```
Male: 1
Female: 2
```

View File

@ -0,0 +1,67 @@
---
title: Exceptions
---
# Exceptions
An exception is an unexpected error that occurs while a program is running, such as an attempt to access a file that does not exist. It will stop the program if not handled.
## Example
If we try to read the text of a file that does not exist:
```
using System.IO;
string content = File.ReadAllText(@"C:\DoesNotExist.txt");
```
A `FileNotFoundException` will be raised.
Some other common exceptions:
* `IndexOutofRangeException`: Attempted to access an array with an invalid index.
* `NullReferenceException`: Attempted to use an unassigned reference variable.
* `DivideByZeroException`: Attempted to divide by 0.
## Best Practices
### Use try/catch/finally Blocks
```
try
{
var client = new WebClient();
var resultData = client.DownloadString("http://github.com");
}
catch (Exception ex)
{
//code for handling exceptions
}
finally
{
//this code is always executed, does not matter if an exception is thrown or not
}
```
### Handle Possible Exceptions With Conditions
Instead of
```
try
{
conn.Close();
}
catch (Exception ex)
{
//code for handling exceptions.
}
```
Try this
```
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
```

View File

@ -0,0 +1,36 @@
---
title: Expression Bodied Methods and Properties
---
# Expression Bodied Methods and Properties
You can declare methods and properties as a lambda expression, without the need for a statement block. Intended for simple implementations, this syntax is more concise than declaring a regular method or property in that it eliminates the need for some of the curly braces and the use of an explicit return statement.
Here is an example of a regular method declaration:
```csharp
public Point CreatePoint(int x, int y)
{
return new Point(x, y);
}
```
The following gives the same result, but is written as an expression bodied method:
```csharp
public Point CreatePoint(int x, int y) => new Point(x, y);
```
You can also declare properties with this syntax. The following code is how we declare a get-only property without a lambda expression:
```csharp
public Point Location
{
get
{
return _location;
}
}
```
Through an expression-bodied method, we can shrink this code down to only one line:
```csharp
public Point Location => _location
```

View File

@ -0,0 +1,43 @@
---
title: Extension Mehods
---
## Extension Methods
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. For client code written in C# there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.
### Usage
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a **using** directive.
### Example
The following example shows an extension method defined for the **System.String** class.
```
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
```
Now you can bring the **WordCount** method to the scope by **using** directive:
```
using ExtensionMethods;
```
And you can call it from an application by using this syntax:
```
string s = "Hello Extension Methods";
int i = s.WordCount();
```
#### More Information:
<a href='https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method' target='_blank' rel='nofollow'>How to: Implement and Call a Custom Extension Method (C# Programming Guide)</a>

View File

@ -0,0 +1,132 @@
---
title: For Loop
---
# For Loop
The for loop executes a block of code repeatedly until a specified conditional expression evaluates to false.
Anatomy of for loop:
```
for (initialization; condition; iterator)
{
body
}
```
- initialization - The initialization statement(s) sets the initial condition and run only once before you enter the body of the loop.
- condition - Boolean expression which determines whether the body of the loop should execute again or the loop should exit.
- iterator - Executes after each iteration of the body of the loop.
### Example 1
```
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Number " + i);
}
```
### Output:
```
> Number 0
> Number 1
> Number 2
> Number 3
> Number 4
```
### Example 2
```
int j = 0;
for (int i = 0; j < 5; i++)
{
Console.WriteLine("Numbers {0} {1}", i, j);
j++;
}
```
### Output:
```
> Numbers 0 0
> Numbers 1 1
> Numbers 2 2
> Numbers 3 3
> Numbers 4 4
```
### Example 3 - Simplification of Example 2
```
for (int i = 0, j = 0; i < 5 && j < 5; i++, j++)
{
Console.WriteLine("Numbers {0} {1}", i, j);
}
```
### Output:
```
> Numbers 0 0
> Numbers 1 1
> Numbers 2 2
> Numbers 3 3
> Numbers 4 4
```
### Example 4
```
for (int i = 5; i > 0; i--)
{
Console.WriteLine("Number " + i);
}
```
### Output:
```
> Number 5
> Number 4
> Number 3
> Number 2
> Number 1
```
### Example 5
```
// Infinite loop - The loop body is executed infinitely
for (; ;)
{
Console.WriteLine("The universe is infinite");
}
// Anything after infinite loop is reported as "Unreachable code detected" in Visual Studio
Console.WriteLine("Never considered for execution");
```
### Output:
```
> The universe is infinite
> The universe is infinite
> The universe is infinite
> ....
> ....
```
### Example 6
```
int i = 0;
for (; i < 5;)
{
Console.WriteLine("Number " + i);
i++;
}
```
### Output:
```
> Number 0
> Number 1
> Number 2
> Number 3
> Number 4
```
### Other Resources
- [Microsoft Documentation](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for)
## End

View File

@ -0,0 +1,44 @@
---
title: For Loop
---
# For Loop
The `for` loop executes a block of code until a specified condition is false. Although a `for` loop looks like a <a href='https://guide.freecodecamp.org/csharp/while-loop' target='_blank' rel='nofollow'>`while` loop</a>, developers should use them __properly__. Use `while` loops when the number of iterations are variable, otherwise use `for` loops. A common use of `for` loops are array iterations.<sup>1</sup>
## Syntax
```C#
for ((Initial variable); (condition); (step))
{
(code)
}
```
The C# for loop consists of three expressions and some code.
## Description
- *Initial Variable*: your starting state, eg int i = 0;
- *Condition*: While this condition is true the code will continue to run, eg i<=5;
- *Step*: The increment, or decrement, of the initial variable, eg i++ or i-=2.
## Example
```C#
int[] array = { 1, 2, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Item on index {0} is {1}", i, array[i]);
}
```
## Output:
```
> Item on index 0 is 1
> Item on index 1 is 2
> Item on index 2 is 3
> Item on index 3 is 4
> Item on index 4 is 5
```
### Sources
1 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for

View File

@ -0,0 +1,30 @@
---
title: Foreach Loop
---
## Foreach Loop
The `foreach` loop executes a block of code for each item in a collection. The benefit of the `foreach` loop is you need not know how many items are within the collection to iterate through it; you simply tell your `foreach` loop to loop through the collection, as long as there are items within it. It is useful for iterating through lists, arrays, datatables, IEnumerables and other list-like data structures. It can be less efficient than a very well designed `for` loop, but the difference is negligible in most cases.
### Example
```csharp
foreach (element in iterable-item)
{
// body of foreach loop
}
List<string> Names = new List<string>{ "Jim", "Jane", "Jack" }
foreach(string name in Names)
{
Console.WriteLine("We have " + name);
}
```
### Output:
```sh
> We have Jim
> We have Jane
> We have Jack
```

View File

@ -0,0 +1,36 @@
---
title: Garbage Collection
---
## Garbage Collection
#### What is Garbage Collection?
Garbage collection is a process in which programs try to free up memory space that is no longer used by objects and such. Garbage collection is implemented differently for every language. Most high-level programming languages have some sort of garbage collection built-in. Low-level programming languages may add garbage collection through libraries.
As said above, every programming language has their own way of GC. In C programming, developers need to take care of memory allocation and deallocation using `malloc()` and `dealloc()` functions. For C# applications, developers no longer need to take care of GC and it's not recommended as well because .NET framework handles this already.
#### How memory allocation happens?
In C#, memory allocation of objects happens in managed heap and this is taken care by CLR (Common Language Runtime). Memory allocation for the heap is done through win32.dll in Operation System (OS) just like in C. But in C, objects are placed in memory whereever the free space suits the size of object. And the memory mapping works based on Linkedlist concepts. In C#, memory allocation for heap happens in linear manner, i.e., one after another.
Whenever a new object is created, a memory is allocated in the heap and the pointer moves to next memory address. Memory allocation in C# is faster than the C. In C the memory needs to search and allocate for the object which adds some overhead time.
#### Generations in C# GC
In .net programming, heap has three generations called Generation 0, 1, 2.
Generation 0 get filled first whenever new object is create. Garbage collector run when the Generation 0 get filled. newly created objects are placed in Generation 0. While performing garbage collection all the unwanted objects are destroyed, memory gets freed and compacted. GC takes care of pointing the pointers of freed memory once GC happens.
Generations 1 and 2 has object which has the longer life time. GC on generations 1 and 2 will not happen until the generations 0 has sufficient memory to allocate.
Its not advisable to invoke the GC programmatically. It's good to let it happen on its own. GC is executed whenever the generation 0 gets filled. GC does not impact the performance of the application.
Garbage collection is the process in which programs try to free up memory space that is no longer used by variables, objects, and such. Garbage collection is implemented differently for every language. Most high-level programming languages have some sort of garbage collection built in. Low-level programming languages may add garbage collection through libraries.
Garbage collection is a tool that saves time for the programmer, for example it replaces the need for functions such as malloc() and free() which are found in C. It can also help in preventing memory leaks.
The downside of garbage collection is that it has a negative impact on performance. The program has to regularly run though the program, checking object references and cleaning out memory - this takes up resources and often requires the program to pause.
If an object has no references (is no longer reachable) then it is eligible for garbage collection. For example in the Java code below, the Thing object originally referenced by 'thing1' has its one and only reference redirected to another object on the heap - it is then unreachable and will have its memory unallocated by the garbage collector.
#### More Information:
-<!-- Please add any articles you think might be helpful to read before writing the article -->
+- https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals - To know more about garbage Collection

View File

@ -0,0 +1,35 @@
---
title: Hello World
---
# Hello World
To write some text on the console we use the `Console.WriteLine()`. This method takes a string as input.
## Example
```csharp
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
// Write "Hello World!" on console
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
```
## Output:
```sh
> Hello World!
> Press any key to exit.
```

View File

@ -0,0 +1,40 @@
---
title: If Else Statement
---
# If Else Statement
The If-Else statement executes a block of code depending on whether your precondition is fullfilled or not.
## Example
```
if(boolean expression)
{
// execute this code block if expression evalutes to true
}
else
{
// always execute this code block when above if expression is false
}
int Price = 30;
If (Price = 30)
{
Console.WriteLine("Price is equal to 30.");
}
Else
{
Console.WriteLine("Price is not equal to 30.");
}
```
Since we already declared our int Price to be 30, this will be the expected output.
## Output
```
Price is equal to 30.
```

View File

@ -0,0 +1,100 @@
---
title: If
---
# If
The if statement executes different blocks of code based on conditions.
```
if (condition)
{
// Do something when `condition` is true
}
else
{
// Do something when `condition` is false
}
```
When `condition` is true, code inside the `if` section executes, otherwise `else` executes. Sometimes you would need to add a second condition. For readability, you should use `else if` rather than nesting `if` statements.
instead of writing:
```
if (condition)
{
// Do something if `condition` is true
}
else
{
if (anotherCondition)
{
// Do something if `anotherCondition` is true
}
else
{
// Do something if `condition` AND `anotherCondition` is false
}
}
```
You could use the much more concise writing:
```
if (condition)
{
// Do something if `condition` is true
}
else if (anotherCondition)
{
// Do something if `anotherCondition` is ture
}
else
{
// Do something if `condition` AND `anotherCondition` is false
}
```
It is also possible to check if the condition is false and act on it without it having to have an else statement.
```
if(!condition)
{
//do something if the condition is false
}
```
```
int number = 3;
//!= implies that you wish to check if the object's value is not equal to the value next to it
if(number !=2)
{
Console.WriteLine("Number is not 2");
}
```
Note that the `else` and `else if` sections are not required, while `if` is mandatory.
## Example
```
Console.WriteLine("Who are you? ");
string name = Console.ReadLine();
if (name == "John")
{
Console.WriteLine("Hi John!");
}
else if (name == "Fabio")
{
Console.WriteLine("Oh, it's you Fabio :)");
}
else
{
Console.WriteLine("Oh! I thought you were John or Fabio. Anyway, nice to meet you {0}!", name);
}
/* Run and type some names:
-> If name is "John", then output is "Hi John!"
-> If name is "Fabio", then output is "Oh, it's you Fabio :)"
-> If name is neither "John" nor "Fabio", output is "Oh! I thought you were John or Fabio. Anyway, nice to meet you {0}!" where {0} contains the name.
*/
```
The if statement needs a boolean result, that is, true or false. In some programming languages, several datatypes can be automatically converted into booleans, but in C#, you have to specifically make the result boolean. For instance, you can't use if(number), but you can compare number to something, to generate a true or false.

View File

@ -0,0 +1,35 @@
---
title: Indeterminate parameters
---
# Indeterminate parameters
Let's imagine we need to write a method where the number of parameters are variable. How can we do that? Well, C# (and other languages) has an easy way to do so; by using the `params` keyword on a method's parameter we can call that method with a variable number of parameters.
## Example
```
public static void Main (string[] args) {
// Call PrintParams with 3 parameters
PrintParams(1, 2, 3);
// Call PrintParams with 1 parameter
PrintParams(4);
}
public static void PrintParams(params int[] values)
{
// Iterate through parameters
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine("Parameter {0} is {1}", i, values[i]);
}
}
```
## Output:
```
> Parameter 0 is 1
> Parameter 1 is 2
> Parameter 2 is 3
> Parameter 0 is 4
```

View File

@ -0,0 +1,65 @@
---
title: C#
---
## C#
C Sharp, more commonly referred to as "C#", is a general-purpose, object-oriented programming language. C# was developed by Anders Hejlsberg and his development team at Microsoft and is currently on version 7.0.
C# has its roots in the family of C languages. It inherits most of its features from C, C++, and Java. For this reason, programmers familiar with these languages may be able to get up to speed with C# in a shorter time span.
C# is an object-oriented language that provides support for component-oriented and functional programming.
#### Classes and Objects
Classes allow us to model everyday objects in the world around us in software. You can create custom classes to represent just about anything. Just like a noun is a person, place or thing in language, so too, a classes represents objects.
When you write C# code, typically it is because you need a program that DOES something useful. In the case of a business need, you follow requirements that the business needs. Say your business comes to you asks you for an electronic database of books. They need to be able to store book titles, authors, compute statistics, like the number of checkouts in a given month, or a monthly average. The requirements describe the program that needs to be developed. How do you write a program for the given requirements? Generally, we use classes to create abstractions for the different nouns that we need to work with. A noun such as a book, author, or title.
An important concept in C# is that the class definition is used to create instances of objects. You can think of it like a blueprint for creating instances of objects. The class definition allows the creation of objects that store a reference to that object. For example, say we want to create a new book object. The line of code looks like this: <br>
<code>
Book book = new Book();
</code><br>
This creates a new book object that we can use to manipulate data and store it in a database. The variable, book, is actually a reference type of Book (with a capital B). We can use methods available in the class definition with that variable, book, such as AddTitle() or AddAuthor() etc.
#### Features of C# include:
1. Automatic Garbage Collection
2. Exception Handling
3. Type-safety
4. Versioning
5. Delegates
6. Properties
7. LINQ (Language-Integrated Query) and Lambda Expressions
8. Generics
9. Indexers
10. Multithreading
#### New Features Added in C# 7.0:
1. Deconstructors
2. New syntax to work with Tuples
3. Pattern Matching with Is Expressions
4. Local Functions
5. Return by Reference
6. Out Variables
7. Literal improvements
8. Generalized Async Return Types
9. More Expression-Bodied Members
10. Throw Expressions
11. Record Type
12. Minimizing OUT
13. Non-'NULL' able reference type
You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much more.
#### ASP.NET and .NET Applications
The C# language is also used with the ASP.NET framework, developed by Microsoft Corp., specifically for creating web applications that are machine and browser independent. The broader .NET framework, also developed by Microsoft, is used for creating other types of applications such as desktop, mobile, server, and networking applications. The .NET framework includes the .NET Base Class Libraries (BCL), ASP.NET, ADO.NET, Windows Forms, Windows Presentation Foundation (WPF), and eXtensible Markup Language(XML) libraries.
For more information on ASP.NET, see the topic, ASPNET in the <a href='https://guide.freecodecamp.org/' target='_blank' rel='nofollow'>freeCodeCamp guide</a>
#### More Information:
* [Introduction to C#](https://docs.microsoft.com/en-us/dotnet/csharp/getting-started/introduction-to-the-csharp-language-and-the-net-framework)
* [C# Tutorials](https://www.microsoft.com/net/tutorials/csharp/getting-started)
* [Official C# Documentation](https://docs.microsoft.com/en-us/dotnet/csharp/)
* [New Features in C# 7.0](https://msdn.microsoft.com/en-us/magazine/mt790184.aspx)

View File

@ -0,0 +1,61 @@
---
title: Inheritance
---
# Inheritance
Inheritance allows you to create a class that extends or modifies an existing class. This can be used to make classes that derive off of other classes.
# Base class and Derived class
These are the terms used for classes when referring to inheritance. The derived class inherits the base class, along with any variables, functions or processes that the base class uses. The derived class can then have its own variables and functions alongside the ones it inherits off the base class.
For example, a Base class of 'Animal' can have a derived class of 'Dog'. The Animal class will contain features relating to animals in general, while the Dog class contains features unique to dogs. When the Dog class inherits the Animal class, it will be able to refer to both features relating to animals and features unique to dogs.
# Rules of Inheritance
Inheritance is one way. The base class does not inherit the features of the derived class.
Inheritance is transitive. A Base class of 'Animal' can have a derived class of 'Dog' and this can have a derived class of 'Terrier'. The Terrier class will inherit both the features of the Dog class and the Animal class.
# The `:` symbol
In C# the `:` symbol is used to denote inheritance. This is called when creating the derived class.
## Example
# Base class
```
public class Animal
{
public int ID;
public string title;
public enum phylum;
public enum dietType;
public DefineAnimal(int id, string name, enum phy, enum diet)
{
this.ID = id;
this.title = name;
this.phylum = phy;
this.dietType = diet;
}
}
```
# Derived class
```
public class Dog : Animal
{
public enum breed;
public int levelOfTraining;
public void SayWoof()
{
Console.WriteLine("Woof");
}
}
```
<!--- To do - Constructor rules, Abstract, Sealing derived classes--->

View File

@ -0,0 +1,57 @@
---
title : Interface
---
---
An interface is similar to a class or struct but without implementation for its members.
An interface declares a contract or a behavior that implementing classes should have.
It may declare only properties, methods and events with NO access modifiers.
All the declared members must be implemented in the inharit class, otherwise will have an compile error.
as a convention we will mark interface with the letter I at the begenning (IMyInterface || IUserOptions).
You define an interface by using the interface keyword.
All members of an interface are:
implicitly abstract,
implicitly public, cannot declare an access modifier such as protected, internal private etc...
An Interface can:
* Inherit from other interfaces.
* Inherit from multiple interfaces at the same time
* Contain only methods, properties, events, and indexers.
An Interface can not :
* Inherit from a class.
* Have implementation.
* Have access modifiers other than public.
* Be instantiated.
---
Using interfaces allows us to change our implementation in our project without breaking other parts,
and only have to change the one place where the object is created.
Interface Example:
```csharp
public Interface IUserFavoriteFood
{
void AddFood();
Task<User> EatFavoriteFood(int id);
}
```
---
Interface inheritance and implementation:
```csharp
public class UserHungry : IUserFavoriteFood
{
public AddFood()
{
// Implementation:
// A method to add food.
}
public Task<User> EatFavoriteFood(int id)
{
// Implementation:
// A method to Eat food by id.
}
}
```

View File

@ -0,0 +1,9 @@
---
title: is
---
## is
The `is` keyword checks if an object is compatible with a given type, or (starting with C# 7) tests an expression against a pattern.
#### More information:
- [C# Reference: is](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/is)

View File

@ -0,0 +1,30 @@
---
title: All
---
# All
Returns true if all the elements in the collection matches the predicate.
### Signature
```csharp
public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// All Fruit have a quantity greater than 0.
var allFruitsHaveAQuantity = fruits.All(f => f.Quantity > 0); // true
// All Fruit have the Color Yellow
var allYellow = fruits.All(f => f.Color == "Yellow"); // false
```

View File

@ -0,0 +1,37 @@
---
title: Any
---
# Any
Returns true if there is at least one element that matches the predicate.
When using an empty predicate (just .Any() without anything between the parantheses) it will return true if the collection is not empty.
### Signature
```csharp
public static bool Any<TSource>(this IEnumerable<TSource> source);
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Check if any Fruits have a quantity greater than 20
var anyFruitGreaterThanTwenty = fruits.Any(f => f.Quantity > 20); // true
// Any Fruit with color Green
var anyGreen = fruits.Any(f => f.Color == "Green"); // false
var hasFruits = fruits.Any(); // true
var hasYellowFruit = fruits.Any(f => f.Color == "Yellow"); // true
```

View File

@ -0,0 +1,24 @@
---
title: Count
---
# Any
Returns a count of elements in the sequence that satisfy a condition.
### Signature
```csharp
Enumerable.Count<TSource> Method (IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Count of Fruit with Color Red.
var yellowCount = fruits.Count(f => f.Color == "Red"); // 2
// Count of Fruit with Quantity > 2
var quantityOverTwo = fruits.Count(f => f.Quantity > 2); // 4
```

View File

@ -0,0 +1,28 @@
---
title: First Or Default
---
# FirstOrDefault
Returns the first element that satisfies an optional given condition. If no element is found, the ```default()``` of the object is returned
### Signature
```csharp
Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
var firstFruit = fruits.FirstOrDefault(); // Orange
var firstYellowFruit = fruits.FirstOrDefault(f => f.Color == "Green"); // null
```

View File

@ -0,0 +1,29 @@
---
title: First
---
# First
Returns the first element that satisfies an optional given condition. If no element is found, throws an ```InvalidOperationException```;
### Signature
```csharp
Enumerable.First<TSource>(IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
var firstFruit = fruits.First(); // Orange
var firstYellowFruit = fruits.First(f => f.Color == "Yellow"); // Pineapple
```

View File

@ -0,0 +1,62 @@
---
title: LINQ
---
# LINQ (Language Integrated Query)
LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a DataSet, a list, a dictionary, etc.
## Example
LINQ can be used to filter, transform, search data and a lot more of complex tasks. Let's say we have the following list of objects:
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
}
```
Then we can do things like:
```csharp
// Get the name of the first fruit
var firstName = fruits.Select(f => f.Name).First(); // Orange
// Count how many fruits are red
var qntRed = fruits.Where(Color == "Red").Count(); // 2
// Create a list of yellow fruits
var yellowFruits = fruits.Where(f => f.Color == "Yellow").ToList(); // { Pineapple, Mango }
// Orders list by quantity from most to less
var orderedFruits = fruits.OrderByDescending(f => f.Quantity).ToList(); // {Grape, Strawberry, Orange, Apple, Mango, Pineapple}
// Sum the quantity of fruits
var quantity = fruits.Sum(f => f.Quantity); // 53
// Check if there are any green fruits
var hasGreen = fruits.Any(f => f.Color == "Green"); // false
// Group fruits by color into a dictionary
var fruitsByColor = fruits.GroupBy(g => g.Color).ToDictionary(k => k.Key, v => v.ToList()); // Dictionary of list of fruits by color
// linq operations can be concatenated and are not performed as long as data is needed
var logs = new List<Log>;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
//IQueryable
if (filterByUser)
logs = logs.Where(p => p.User == user);
//IQueryable
result = logs.ToList();
//List<log>
```

View File

@ -0,0 +1,24 @@
---
title: LastOrDefault
---
# Any
Returns the last element in a sequence that satisfies a condition or a default value if no element is found
### Signature
```csharp
Enumerable.LastOrDefault<TSource> Method (IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Returns the last fruit where the Color is Yellow
var lastYellow = fruits.LastOrDefault(f => f.Color == "Yellow"); // Mango
// Returns the last fruit where the quantity is 20
var lastQuantityOfTwenty = fruits.LastOrDefault(f => f.Quantity == 20); // null
```

View File

@ -0,0 +1,28 @@
---
title: Select
---
# Select
Projects data from the data set.
### Signature
```csharp
Enumerable.Select<TSource,TResult> Method (IEnumerable<TSource>,Func<TSource,TResult>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity = 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity = 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity = 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity = 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity = 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity = 2 }
};
var mangoQnt = fruits.Where(f => f.Name == "Mango").Select(f => f.Quantity).FirstOrDefault(); // 2
var grapeColor = fruits.Where(f => f.Name == "Grape").Select(f => f.Color).FirstOrDefault(); // Purple
```

View File

@ -0,0 +1,28 @@
---
title: Single Or Default
---
# SingleOrDefault
Returns the single element in a sequence that satisfies the specified condition or the default value if no element is found. The method will throw an exception if more than one element is found that satisfies the specified condition.
### Signature
```csharp
Enumerable.SingleOrDefault<TSource>(IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
var purpleFruit = fruits.SingleOrDefault(f => f.Color == "Purple"); // Grape
var greenFruit = fruits.SingleOrDefault(f => f.Color == "Green"); // null
```

View File

@ -0,0 +1,33 @@
---
title: To Dictionary
---
# ToDictionary
Greates a Dictionary from the DataSet;
### Signature
```csharp
Enumerable.ToDictionary<TSource,TKey> Method (IEnumerable<TSource>,Func<TSource,TKey>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Generates a Dictionary of Fruits by Id
var fruitsById = fruits.ToDictionary(k => k.Id, v => v); // Dictionary<int, Fruit>
// Generates a dictionary fruits by color
var fruitsByColor = fruits.GroupBy(g => g.Color).ToDictionary(k => k.Key, v => v.ToList()); // Dictionary of list of fruits by color
// Generates a dictionary of quantity of fruits by color
var fruitsByColor = fruits.GroupBy(g => g.Color).ToDictionary(k => k.Key, v => v.Sum(s => s.Quantity)); // Dictionary of sum of fruits by color
```

View File

@ -0,0 +1,27 @@
---
title: To List
---
# ToList
Generates a List given the DataSet queries.
### Signature
```csharp
Enumerable.ToList<TSource> Method (IEnumerable<TSource>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Generates list of fruits name
var fruitsNames = fruits.Select(f => f.Name).ToList(); // { "Orange", "Strawberry", "Grape", "Pineapple", "Apple", "Mango" }
```

View File

@ -0,0 +1,30 @@
---
title: Where
---
# Where
Filters elements from the dataset.
### Signature
```csharp
Enumerable.Where<TSource> Method (IEnumerable<TSource>,Func<TSource,Boolean>)
```
## Example
```csharp
var fruits = new List<Fruit>() {
new Fruit() { Id = 1, Name = "Orange", Color = "Orange", Quantity: 3 },
new Fruit() { Id = 2, Name = "Strawberry", Color = "Red", Quantity: 12 },
new Fruit() { Id = 3, Name = "Grape", Color = "Purple", Quantity: 25 },
new Fruit() { Id = 4, Name = "Pineapple", Color = "Yellow", Quantity: 1 },
new Fruit() { Id = 5, Name = "Apple", Color = "Red", Quantity: 5 },
new Fruit() { Id = 6, Name = "Mango", Color = "Yellow", Quantity: 2 }
};
// Fruits with more than 3 items
var moreThanThree = fruits.Where(f => f.Quantity > 3).ToList(); // { Strawberry, Grape, Apple }
// Fruits that are not red
var notRed = fruits.Where(f => f.Color != "Red").ToList(); // { Orange, Grape, Pineapple, Mango }
```

View File

@ -0,0 +1,20 @@
---
title: Literal Improvements
---
# Literal Improvements
C# 7.0 allows _ to occur as a ***digit separator*** inside number literals:
```
var d = 123_456;
var x = 0xAB_CD_EF;
```
You can put them wherever you want between digits, to improve readability. They have no effect on the value.
Also, C# 7.0 introduces ***binary literals***, so that you can specify bit patterns directly instead of having to know hexadecimal notation by heart.
```
var b = 0b1010_1011_1100_1101_1110_1111;
```

View File

@ -0,0 +1,51 @@
---
title: Method Overloading
---
# Method Overloading
Default parameters were introduced in C# version 4.0, but up until that, C# coders have been using a different technique, which basically does the same, called method overloading. It allows the programmer do define several methods with the same name, as long as they take a different set of parameters. When you use the classes of the .NET framework, you will soon realize that method overloading is used all over the place.
## Example
1. Create a class file named Person.cs & input the following code.
```
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string SayHello(string name)
{
return "Hello there, " + name;
}
public string SayHello(Person person)
{
return "Hello there, " + person.FirstName + " " + person.LastName;
}
}
```
2. In your default Program.cs file you can call now this class Person using the method overloading.
```
class Program
{
static void Main(string[] args)
{
Person person = new Person("Jane", "Doe");
Console.WriteLine(person.SayHello("Peter Smith"));
Person friend = new Person("Chuck", "Norris");
Console.WriteLine(person.SayHello(friend));
Console.ReadKey();
}
}
```

View File

@ -0,0 +1,30 @@
---
title: nameof Expressions
---
# nameof Expressions
Sometimes you need the string name of a variable, type, or member for things such as raising an exception, logging, or firing property changed events. Prior to C# 6.0, you might use a string literal for such purposes.
##
```
public void ProcessStudent(Student student)
{
if (student == null) throw new ArgumentNullException("student");
}
```
However, if the student parameter were to be renamed, you would have to remember to also modify the string literal. Now with nameof expressions, you dont have to use string literals and the compiler will be able to warn you if you are using an incorrect name.
##
```
public void ProcessStudent(Student student)
{
if (student == null) throw new ArgumentNullException(nameof(student));
}
```
Some examples of where nameof expressions may be useful include:
* Throwing exceptions during parameter validation
* Passing an action name when setting up MVC action links
* Needing to pass the name of a property when firing a property changed event in a class that implements INotifyPropertyChanged
* Passing the name of a property when registering a XAML dependency property
* Including a variable, type, or member name when logging
It should be noted that if you provide nameof with a qualified name, the compiler will generate a string for the rightmost name.

View File

@ -0,0 +1,26 @@
---
title: Nested If Statement
---
# Nested If Statement
The Nested If Statement is used when upon creating an if statement you want a secondary point of validation or if statement inside of it.
```
int Price = 100;
int Quantity = 20;
if (Price == 100)
{
if (Quantity == 20)
{
Console.WriteLine("Price of an item is 200, and we have 20 in quantity.");
}
}
```
Therefore since we've predetermined Price and Quantity the output would be:
```
Price of an item is 200, and we have 20 in quantity.
```

View File

@ -0,0 +1,76 @@
---
title: Null-coalescing Operator
---
# Null-coalescing Operator
The null-coalescing operator in C# is used to help assign one variable to another and specify an alternate value if the source value is `null`. The null-coalescing operator in C# is `??`.
## Example 1
Since `name` is `null`, `clientName` will be assigned the value "John Doe".
```cs
string name = null;
string clientName = name ?? "John Doe";
Console.WriteLine(clientName);
```
```cs
> John Doe
```
## Example 2
Since `name` is not `null`, `clientName` will be assigned the value of `name`, which is "Jane Smith".
```cs
string name = "Jane Smith";
string clientName = name ?? "John Doe";
Console.WriteLine(clientName);
```
```cs
> Jane Smith
```
## Alternative to if...else Statement
You could use an `if...else` statement to test for the presence of `null` and assign a different value.
```cs
string clientName;
if (name != null)
clientName = name;
else
clientName = "John Doe";
```
However, this can be greatly simplified using the null-coalescing operator.
```cs
string clientName = name ?? "John Doe";
```
## Alternative to Conditional (Ternary) Operator
It is also possible to use the conditional operator to test for the presence of `null` and assign a different value.
```cs
string clientName = name != null ? name : "John Doe";
```
Again, this can be simplified using the null-coalescing operator.
```cs
string clientName = name ?? "John Doe";
```
## References
* [?? Operator (C# Reference)](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator)

View File

@ -0,0 +1,61 @@
---
title: Null-conditional Operator
---
# Null-conditional Operator
Null-conditional operators allow for null checking with a minimal amount of code. For example, if you had
an employee variable of type Employee with a property of type Address, you might do null checking as follows:
```csharp
Address address = null;
if (employee != null)
{
address = employee.Address;
}
```
You could use a standard conditional operator to make that check more concise:
```csharp
Address address = employee != null ? employee.Address : null;
```
However, in C# 6.0 null-conditional operators were introduced, so now the above line can simply
be represented as follows:
```csharp
Address address = student?.Address;
```
If employee is null, address will simply be assigned null, and no NullReferenceExeception will occur.
This becomes more useful with deeper object graphs, as you can handle a chain of conditional member access.
For example:
```csharp
string city = student?.Address?.City;
```
Null-conditional operators are short-circuiting, so as soon as one check of conditional member access
returns null, the rest do not take place.
# Null-coalescing operator
Another useful null-checking option is the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
For example:
```csharp
public string GetStringValue()
{
return null;
}
// Display the value of s if s is NOT null. If x IS null, display the string "It was null."
string x = GetStringValue();
Console.WriteLine(x ?? "It was null.");
// Result:
"It was null."
```

View File

@ -0,0 +1,33 @@
---
title: Nullable Types
---
## Nullable Types
Nullable types are instances of the [System.Nullable\<T\>](https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1) struct.
A nullable type can represent the correct range of values for its underlying value type, plus an additional `null` value.
This ability is very useful when you are dealing with databases or other data types that may contain elements without assigned value.
#### How to use nullable type
```csharp
// Declare a variable of Nullable type (Nullable<int>)
int? i = null;
int j = 0;
int defaultValue = 0;
// test for null and assign value to another variable
if (i.HasValue)
{
j = i.Value;
}
// get assigned value or default when current value is null
j = i.GetValueOrDefault(); // i.GetValueOrDefault(defaultValue)
//use coalescing operator to assign default value when current value is null
j = i ?? defaultValue;
```
For more information, visit the following link:
- [C# Programming Guide: Nullable Types](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/)

View File

@ -0,0 +1,38 @@
---
title: Return Statement
---
# Return Statement
The `return` statement terminates execution of a method inside which it appears and returns control to the calling method. It may or may not return a value.
If the `return` statement is inside a `try` block and if there is a `finally` block, then the control is passed to the `finally` block, after which it is returned to the calling method.
## Example
```
class Calc
{
static int Sum(int i, int j)
{
return i + j;
}
static void Main()
{
int a = 4;
int b = 3;
int sum = Sum(a, b);
Console.WriteLine($"The sum of {a} and {b} is {result}");
// To keep the console from closing
Console.ReadLine();
}
}
```
## Output:
```
> The sum of 4 and 3 is 7
``

View File

@ -0,0 +1,32 @@
---
title: Split
---
# Split Method
The `String.Split` method parses a string: As input, it takes a character indicating the separator, and generates an array of sub strings.
## Example
```csharp
string myText = "I like pizza";
// Split the string by ' '(space) character.
string[] splitResult = myText.Split(' ');
// The array splitResult, now contains three substrings.
// Now print the array of substrings
foreach(string x in splitResult)
{
// Write On Console
Console.WriteLine(x);
}
```
## Output:
```
> I
> like
> pizza
```

View File

@ -0,0 +1,26 @@
---
title: String Interpolation
---
# String Interpolation
In C#, typically to concatenate strings you would either use the “+” operator or composite formatting with a method such as String.Format. By composite formatting I am referring to a format string with indexed placeholders (format items) and a list of objects to be used in the placeholders.
##
```
string message = "Hello " + firstName + " " + lastName + "!";
string message2 = string.Format("Hello {0} {1}!", firstName, lastName);
```
With interpolated string expressions, you have a string with contained expressions that are replaced with the expressions results. You have to prefix your string literal with a dollar sign ($). The expressions you want included in the string are placed inline enclosed in curly braces. The above message would now look like this:
##
```
string message = $"Hello {firstName} {lastName}!";
```
**Small Bit Of Useful Information**
In string interpolation you have the ability to call functions, properties and ternary operators:
```
int a = 3;
int b = 454;
string result = $"{a}+{b} = {a+b}";
```

View File

@ -0,0 +1,26 @@
---
title: Substring
---
# Substring
`Substring` extracts a portion of a string value. It is used with 2 integer parameters, the first is location of the first character(starts with index 0) and the second is the desired character length.
## Example
```
string firstSentence = "Apple, I have.";
string secondSentence = "I have a Pen.";
string apple = firstSentence.Substring(0,5);
string pen = secondSentence.Substring(9,3);
Console.WriteLine(apple);
Console.WriteLine(pen);
```
## Output:
```
>Apple
>Pen
```

View File

@ -0,0 +1,64 @@
---
title: Switch Case
---
# Switch Case
Switch is a selection statement that chooses a switch case section depending on the value matched with the expression/value being evaluated.<sup>1</sup> If none of the case statements match the value of the switched variable, the default path is chosen. The switch statement is like a set of `if statements`. We exit from the switch by `break`.
## Example
```
public enum Colors { Red, Blue, Green, Orange }
Colors myColor;
... myColor is set to one of the enum values ...
switch(myColor){
case Colors.Red:
Console.WriteLine("How you like them apples?");
break;
case Colors.Blue:
Console.WriteLine("Ice Ice Baby...");
break;
case Colors.Green:
Console.WriteLine("Fore!");
break;
default:
Console.WriteLine("I have a hard time when I try to rhyme.");
}
```
## Output
```
If myColor is Colors.Red:
> How you like them apples?
If myColor is Colors.Blue:
> Ice Ice Baby...
If myColor is Colors.Green:
> Fore!
If myColor is Colors.Orange:
> I have a hard time when I try to rhyme.
```
## Fallthrough
It is also possible to use multiple statements produce the same outcome, by letting the cases 'fallthrough', like so:
```
switch(myColor) {
case Colors.Red:
case Colors.Blue:
//Code
break;
...
}
```
This will execute the same lines of code if myColor is either Red or Blue.
### Sources:
- 1 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch

View File

@ -0,0 +1,40 @@
---
title: Ternary operator
---
# Ternary operator (`?:`)
Ternary operator return one of the two expression based on the condition. It can be used as a shortcut for if...else statement.
## Syntax
```
condition_expression ? expression_1 : expression_2
```
### Parameter
`condition_expression`
Boolean expression.
`expression_1`
Returned if `condition_expression` is true.
`expression_2`
Returned if `condition_expression` is false.
## Example
```
// initialize - set true or false here to view different result
bool hasFreeSweet = false;
string str = hasFreeSweet ? "Free sweet!" : "No free sweet.";
//output in console
Console.WriteLine(str);
```
## Output
```
if hasFreeSweet == true
> Free sweet!
if hasFreeSweet == false
> No free sweet.
```

View File

@ -0,0 +1,100 @@
---
title: Try Catch Finally
---
# Try Catch Finally
A Try-Catch-Finally block is used to avoid unhandled exceptions breaking your application. When your code ```throws``` an exception which sits between the ```try``` section it will be caught in the ```catch``` part of the statement, where you can handle it as you wish. The ```finally``` statement is always run at the end and is usually used to clean up unmanaged resources. You don't always need to have the three blocks present, below are the valid options.
* Try-Catch-Finally
* Try-Catch
* Try-Finally
## Syntax
```csharp
try
{
// Code which could potentially throw an exception
var parsedValue = Int32.Parse("abcde");
}
catch(Exception e)
{
// Code to handle the exception
Console.WriteLine("Exception: " + e.Message);
}
finally
{
// Code which will always run no matter what.
Console.WriteLine("Try-Catch block has finished execution");
}
```
In the example above we are trying to convert 'abcde' into a numerical value. This line will throw an exception because it cannot be converted to a number successfully. The execption will be caught in the catch block and the exception message and other details will be stored in the variable assigned in the catch block (The letter 'e' in the example above). After all this has been executed the "finally" section will be executed to finish it off.
## Try block
The try block should be placed around code which could behave out of the ordinary and cause an ```Exception``` and break your application. By having a try block you protect yourself from a fatal application crash. It is important to note as soon as your application has an error and an exception is thrown, the rest of the code in the ```Try``` block will **not** be executed.
A try block has its own method scope, so any variables which are declared inside the try block will not be accessible outside of the try block.
```csharp
try
{
// Read user input from the console.
var userInput = Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
//Outside the Try block
var parsedUserInput = Int32.Parse(userInput); // Not correct
```
The above will give you a compile time error as the value 'userInput' is not accessible. If you need access to a variable outside the try-catch block you will need to declare the variable before the try block.
```csharp
var userInput = "";
try
{
// Read user input from the console.
userInput = Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
//Outside the Try block
var parsedUserInput = Int32.Parse(userInput); // Correct
```
## Catch block
This block is where you specify what type of ```Exception``` you want to catch. If you want to catch ALL possible exceptions you can use the ```Exception``` base class. If you want to only catch a specific type of exception you can specify that instead. Some examples of other exception types are ```ArgumentException```, ```OutOfMemoryException ``` and ```FormatException```.
```csharp
try
{
var parsedValue = Int32.Parse("abcde");
}
// Only FormatExceptions will be caught in this catch block.
catch(FormatException exceptionVariable)
{
Console.WriteLine(exceptionVariable.Message);
}
```
The variable declared after the type of exception will contain all the data of the exception and can be used within the ```Catch``` block.
## Finally block
The finally block is **always** run at the end after the ```Try``` and ```Catch``` blocks. This section is usually used to when something **must** happen at the end regardless if an exception was thrown or not.
For example, say we need a variable to always be re-initalised back to a specific number after it has been manipulated all the time.
```csharp
int initalValue = 12;
try
{
// Code which manipulates 'initialValue'
}
finally
{
Console.WriteLine("re-initalising value back to 12");
initialValue = 12;
}
```

View File

@ -0,0 +1,54 @@
---
title: While Loop
---
# While Loop
The while loop executes a block of code until a specified condition is false. Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times. This differs from the do loop, which executes one or more times because the test of the expression takes place after the execution of the loop.<sup>1</sup>
## Example
```csharp
int i = 0;
while (i < 5)
{
Console.WriteLine("Number " + i);
i++;
}
```
### Output:
```
> Number 0
> Number 1
> Number 2
> Number 3
> Number 4
```
## Other Uses
The while loops is often used for infinite iterrations by using (for example) `while (true)`, only to be ended through a condition unrelated to the initial condition of the loop.
```csharp
int i = 0;
while (true)
{
if(i<50){
Console.WriteLine("Number " + i);
i++;
}
else{
Console.WriteLine("End of loop");
break;
}
}
```
## Differences to the `for` loop
The biggest differences between the `for` and `while` loops is that `while` is typically used when a developer is not sure of an exact number of iterations of the loop, and `for` is used when it's clear how many times to iterate through code.
### Sources
* [Microsoft C# - while](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while)

View File

@ -0,0 +1,39 @@
---
title: Xaml
---
## XAML: Extensible Application Markup Language
XAML pronounced as "Zammel" is a mark language developed by Microsoft. This markup language is mainly used for designing GUIs. Also it is popular for its usability in workflow.
Areas like Silverlight, Mobile Development, WPF (Windows Presentation Foindation), Windows Store uses XAML heavily and span accross any CLR and .NET framework
Its a declaritive language and answers WHAT and HOW. It aims at separating the behavior from the designer code.
## Example
Creating a TextBlock with several properties. TextBlocks are usually employed for the output of text, much like Labels in older versions of the .NET framework.
```xml
<TextBlock Text="I am a TextBlock!"
HorizontalAlignment="Left"
FontSize="25"
FontWeight="Bold"
Margin="50,10,0,0" />
```
### Example 2
The following example shows a label with "Hello World!" as its content in a top level container called UserControl.
```XAML
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Label Content="Hello World!" />
</UserControl>
```
### More Information:
* [A Beginners Article about XAML and the WPF Engine](http://www.c-sharpcorner.com/UploadFile/logisimo/a-beginners-article-about-xaml-and-the-wpf-engine/)
* [XAML Magic: Attached Properties](http://www.codemag.com/article/1405061)
* [XAML Overview (WPF)](https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/xaml-overview-wpf)