mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-05-05 14:28:31 +00:00
Merge pull request #948 from Laoujin/master
[CSharp/en]Some fixes and additions
This commit is contained in:
commit
705e40497d
@ -5,6 +5,7 @@ contributors:
|
|||||||
- ["Max Yankov", "https://github.com/golergka"]
|
- ["Max Yankov", "https://github.com/golergka"]
|
||||||
- ["Melvyn Laïly", "http://x2a.yt"]
|
- ["Melvyn Laïly", "http://x2a.yt"]
|
||||||
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
|
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
|
||||||
|
- ["Wouter Van Schandevijl", "http://github.com/laoujin"]
|
||||||
filename: LearnCSharp.cs
|
filename: LearnCSharp.cs
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -18,22 +19,29 @@ C# is an elegant and type-safe object-oriented language that enables developers
|
|||||||
Multi-line comments look like this
|
Multi-line comments look like this
|
||||||
*/
|
*/
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This is an XML documentation comment
|
/// This is an XML documentation comment which can be used to generate external
|
||||||
|
/// documentation or provide context help within an IDE
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
//public void MethodOrClassOrOtherWithParsableHelp() {}
|
||||||
|
|
||||||
// Specify namespaces application will be using
|
// Specify the namespaces this source code will be using
|
||||||
|
// The namespaces below are all part of the standard .NET Framework Class Libary
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data.Entity;
|
|
||||||
using System.Dynamic;
|
using System.Dynamic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Linq.Expressions;
|
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
|
||||||
// defines scope to organize code into "packages"
|
// But this one is not:
|
||||||
namespace Learning
|
using System.Data.Entity;
|
||||||
|
// In order to be able to use it, you need to add a dll reference
|
||||||
|
// This can be done with the NuGet package manager: `Install-Package EntityFramework`
|
||||||
|
|
||||||
|
// Namespaces define scope to organize code into "packages" or "modules"
|
||||||
|
// Using this code from another source file: using Learning.CSharp;
|
||||||
|
namespace Learning.CSharp
|
||||||
{
|
{
|
||||||
// Each .cs file should at least contain a class with the same name as the file
|
// Each .cs file should at least contain a class with the same name as the file
|
||||||
// you're allowed to do otherwise, but shouldn't for sanity.
|
// you're allowed to do otherwise, but shouldn't for sanity.
|
||||||
@ -125,7 +133,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
// Use const or read-only to make a variable immutable
|
// Use const or read-only to make a variable immutable
|
||||||
// const values are calculated at compile time
|
// const values are calculated at compile time
|
||||||
const int HOURS_I_WORK_PER_WEEK = 9001;
|
const int HoursWorkPerWeek = 9001;
|
||||||
|
|
||||||
///////////////////////////////////////////////////
|
///////////////////////////////////////////////////
|
||||||
// Data Structures
|
// Data Structures
|
||||||
@ -242,8 +250,15 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
int fooDoWhile = 0;
|
int fooDoWhile = 0;
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
//Iterated 100 times, fooDoWhile 0->99
|
// Start iteration 100 times, fooDoWhile 0->99
|
||||||
|
if (false)
|
||||||
|
continue; // skip the current iteration
|
||||||
|
|
||||||
fooDoWhile++;
|
fooDoWhile++;
|
||||||
|
|
||||||
|
if (fooDoWhile == 50)
|
||||||
|
break; // breaks from the loop completely
|
||||||
|
|
||||||
} while (fooDoWhile < 100);
|
} while (fooDoWhile < 100);
|
||||||
|
|
||||||
//for loop structure => for(<start_statement>; <conditional>; <step>)
|
//for loop structure => for(<start_statement>; <conditional>; <step>)
|
||||||
@ -301,7 +316,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
// Converting data
|
// Converting data
|
||||||
|
|
||||||
// Convert String To Integer
|
// Convert String To Integer
|
||||||
// this will throw an Exception on failure
|
// this will throw a FormatException on failure
|
||||||
int.Parse("123");//returns an integer version of "123"
|
int.Parse("123");//returns an integer version of "123"
|
||||||
|
|
||||||
// try parse will default to type default on failure
|
// try parse will default to type default on failure
|
||||||
@ -315,6 +330,11 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
Convert.ToString(123);
|
Convert.ToString(123);
|
||||||
// or
|
// or
|
||||||
tryInt.ToString();
|
tryInt.ToString();
|
||||||
|
|
||||||
|
// Casting
|
||||||
|
// Cast decimal 15 to a int
|
||||||
|
// and then implicitly cast to long
|
||||||
|
long x = (int) 15M;
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
@ -367,8 +387,12 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Methods can have the same name, as long as the signature is unique
|
// Methods can have the same name, as long as the signature is unique
|
||||||
public static void MethodSignatures(string maxCount)
|
// A method that differs only in return type is not unique
|
||||||
|
public static void MethodSignatures(
|
||||||
|
ref int maxCount, // Pass by reference
|
||||||
|
out int count)
|
||||||
{
|
{
|
||||||
|
count = 15; // out param must be assigned before control leaves the method
|
||||||
}
|
}
|
||||||
|
|
||||||
// GENERICS
|
// GENERICS
|
||||||
@ -400,6 +424,10 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
|
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
|
||||||
MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
|
MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
|
||||||
|
|
||||||
|
// BY REF AND OUT PARAMETERS
|
||||||
|
int maxCount = 0, count; // ref params must have value
|
||||||
|
MethodSignatures(ref maxCount, out count);
|
||||||
|
|
||||||
// EXTENSION METHODS
|
// EXTENSION METHODS
|
||||||
int i = 3;
|
int i = 3;
|
||||||
i.Print(); // Defined below
|
i.Print(); // Defined below
|
||||||
@ -435,6 +463,31 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
Func<int, int> square = (x) => x * x; // Last T item is the return value
|
Func<int, int> square = (x) => x * x; // Last T item is the return value
|
||||||
Console.WriteLine(square(3)); // 9
|
Console.WriteLine(square(3)); // 9
|
||||||
|
|
||||||
|
// ERROR HANDLING - coping with an uncertain world
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var funBike = PennyFarthing.CreateWithGears(6);
|
||||||
|
|
||||||
|
// will no longer execute because CreateWithGears throws an exception
|
||||||
|
string some = "";
|
||||||
|
if (true) some = null;
|
||||||
|
some.ToLower(); // throws a NullReferenceException
|
||||||
|
}
|
||||||
|
catch (NotSupportedException)
|
||||||
|
{
|
||||||
|
Console.WriteLine("Not so much fun now!");
|
||||||
|
}
|
||||||
|
catch (Exception ex) // catch all other exceptions
|
||||||
|
{
|
||||||
|
throw new ApplicationException("It hit the fan", ex);
|
||||||
|
// throw; // A rethrow that preserves the callstack
|
||||||
|
}
|
||||||
|
// catch { } // catch-all without capturing the Exception
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
// executes after try or catch
|
||||||
|
}
|
||||||
|
|
||||||
// DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
|
// DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
|
||||||
// Most of objects that access unmanaged resources (file handle, device contexts, etc.)
|
// Most of objects that access unmanaged resources (file handle, device contexts, etc.)
|
||||||
// implement the IDisposable interface. The using statement takes care of
|
// implement the IDisposable interface. The using statement takes care of
|
||||||
@ -595,10 +648,26 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
|
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
|
||||||
|
|
||||||
|
// Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
|
||||||
|
[Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc
|
||||||
|
public enum BikeAccessories
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
Bell = 1,
|
||||||
|
MudGuards = 2, // need to set the values manually!
|
||||||
|
Racks = 4,
|
||||||
|
Lights = 8,
|
||||||
|
FullPackage = Bell | MudGuards | Racks | Lights
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell)
|
||||||
|
// Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell
|
||||||
|
public BikeAccessories Accessories { get; set; }
|
||||||
|
|
||||||
// Static members belong to the type itself rather then specific object.
|
// Static members belong to the type itself rather then specific object.
|
||||||
// You can access them without a reference to any object:
|
// You can access them without a reference to any object:
|
||||||
// Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
|
// Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
|
||||||
static public int BicyclesCreated = 0;
|
public static int BicyclesCreated { get; set; }
|
||||||
|
|
||||||
// readonly values are set at run time
|
// readonly values are set at run time
|
||||||
// they can only be assigned upon declaration or in a constructor
|
// they can only be assigned upon declaration or in a constructor
|
||||||
@ -682,7 +751,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
// All though this is not entirely useful in this example, you
|
// All though this is not entirely useful in this example, you
|
||||||
// could do bicycle[0] which yields "chris" to get the first passenger or
|
// could do bicycle[0] which yields "chris" to get the first passenger or
|
||||||
// bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle)
|
// bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle)
|
||||||
private string[] passengers = { "chris", "phil", "darren", "regina" }
|
private string[] passengers = { "chris", "phil", "darren", "regina" };
|
||||||
|
|
||||||
public string this[int i]
|
public string this[int i]
|
||||||
{
|
{
|
||||||
@ -737,10 +806,17 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
}
|
}
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
throw new ArgumentException("You can't change gears on a PennyFarthing");
|
throw new InvalidOperationException("You can't change gears on a PennyFarthing");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static PennyFarthing CreateWithGears(int gears)
|
||||||
|
{
|
||||||
|
var penny = new PennyFarthing(1, 1);
|
||||||
|
penny.Gear = gears; // Oops, can't do this!
|
||||||
|
return penny;
|
||||||
|
}
|
||||||
|
|
||||||
public override string Info()
|
public override string Info()
|
||||||
{
|
{
|
||||||
string result = "PennyFarthing bicycle ";
|
string result = "PennyFarthing bicycle ";
|
||||||
@ -784,7 +860,7 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
|
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
|
||||||
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
|
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class BikeRepository : DbSet
|
public class BikeRepository : DbContext
|
||||||
{
|
{
|
||||||
public BikeRepository()
|
public BikeRepository()
|
||||||
: base()
|
: base()
|
||||||
@ -798,13 +874,15 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
|
|
||||||
## Topics Not Covered
|
## Topics Not Covered
|
||||||
|
|
||||||
* Flags
|
|
||||||
* Attributes
|
* Attributes
|
||||||
* Static properties
|
* async/await, yield, pragma directives
|
||||||
* Exceptions, Abstraction
|
* Web Development
|
||||||
* ASP.NET (Web Forms/MVC/WebMatrix)
|
* ASP.NET MVC & WebApi (new)
|
||||||
* Winforms
|
* ASP.NET Web Forms (old)
|
||||||
* Windows Presentation Foundation (WPF)
|
* WebMatrix (tool)
|
||||||
|
* Desktop Development
|
||||||
|
* Windows Presentation Foundation (WPF) (new)
|
||||||
|
* Winforms (old)
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
|
||||||
@ -817,7 +895,4 @@ on a new line! ""Wow!"", the masses cried";
|
|||||||
* [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
|
* [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
|
||||||
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
|
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
|
||||||
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
|
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
|
||||||
|
* [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)
|
||||||
|
|
||||||
|
|
||||||
[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)
|
|
||||||
|
Loading…
Reference in New Issue
Block a user