From e17ef8b1802c558ab9d77bd03569816dadabd750 Mon Sep 17 00:00:00 2001 From: Irfan Charania Date: Mon, 12 Aug 2013 17:54:53 -0700 Subject: Add C# Language Based on the Java one --- csharp.html.markdown | 550 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 550 insertions(+) create mode 100644 csharp.html.markdown (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown new file mode 100644 index 00000000..d67f6c74 --- /dev/null +++ b/csharp.html.markdown @@ -0,0 +1,550 @@ +--- + +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] +filename: LearnCSharp.cs + +--- + +C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. + +[Read more here.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// Single-line comments start with // +/* +Multi-line comments look like this +*/ +/// +/// This is an XML documentation comment +/// + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// defines scope to organize code into "packages" +namespace Learning +{ + // 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. + public class LearnCSharp + { + // A console application must have a main method as an entry point + public static void Main(string[] args) + { + // Use Console.WriteLine to print lines + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // To print without a new line, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + + /////////////////////////////////////////////////// + // Types & Variables + // + // Declare a variable using + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Signed 16-bit integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Ushort - Unsigned 16-bit integer + // (0 <= ushort <= 65,535) + ushort fooUshort = 10000; + + // Integer - Signed 32-bit integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Uinteger - Unsigned 32-bit integer + // (0 <= uint <= 4,294,967,295) + uint fooUint = 1; + + // Long - Signed 64-bit integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L is used to denote that this variable value is of type long or ulong + // anything without is treated as int or uint depending on size. + + // Ulong - Unsigned 64-bit integer + // (0 <= ulong <= 18,446,744,073,709,551,615) + ulong fooUlong = 100000L; + + // Float - Single-precision 32-bit IEEE 754 Floating Point + // Precision: 7 digits + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + // Precision: 15-16 digits + double fooDouble = 123.4; + + // Bool - true & false + bool fooBoolean = true; + bool barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings + string fooString = "My string is here!"; + Console.WriteLine(fooString); + + // formatting + string fooFormattedString = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + Console.WriteLine(fooFormattedString); + + // formatting dates + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // \n is an escaped character that starts a new line + string barString = "Printing on a new line?\nNo Problem!"; + Console.WriteLine(barString); + + // it can be written prettier by using the @ symbol + string bazString = @"Here's some stuff + on a new line!"; + Console.WriteLine(bazString); + + // quotes need to be escaped + // use \" normally + string quotedString = "some \"quoted\" stuff"; + Console.WriteLine(quotedString); + + // use "" when strings start with @ + string quotedString2 = @"some MORE ""quoted"" stuff"; + Console.WriteLine(quotedString2); + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + // Nullable types + // any type can be made nullable by suffixing a ? + // ? = + int? nullable = null; + Console.WriteLine("Nullable variable: " + nullable); + + // ?? is syntactic sugar for specifying default value + // in case variable is null + int notNullable = nullable ?? 0; + Console.WriteLine("Not nullable variable: " + notNullable); + + // Var - compiler will choose the most appropriate type based on value + var fooImplicit = true; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + Console.WriteLine("\n->Data Structures"); + + // Arrays + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + string[] stringArray = new string[1]; + bool[] boolArray = new bool[100]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + + // Arrays are zero-indexed and mutable. + intArray[1] = 1; + Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + + // Another way to declare & initialize a list + List z = new List { 9000, 1000, 1337 }; + + // Indexing a list - Accessing an element + // Lists are zero-indexed and mutable. + Console.WriteLine("z @ 0: " + z[2]); + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + + // Others data structures to check out: + // + // Stack/Queue + // Dictionary + // Read-only Collections + // Tuple (.Net 4+) + + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 + Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 + Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 + Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + Console.WriteLine("Ternary demo: " + isTrue); + + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Console.WriteLine(fooWhile); + //Increment the counter + //Iterated 99 times, fooWhile 0->99 + fooWhile++; + } + Console.WriteLine("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do + { + //Console.WriteLine(fooDoWhile); + //Increment the counter + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + Console.WriteLine("fooDoWhile Value: " + fooDoWhile); + + // For Loop + int fooFor; + //for loop structure => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) + { + //Console.WriteLine(fooFor); + //Iterated 10 times, fooFor 0->9 + } + Console.WriteLine("fooFor Value: " + fooFor); + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + Console.WriteLine("Switch Case Result: " + monthString); + + + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + int.TryParse("123", out tryInt); + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + Console.WriteLine("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.ToString()); + + // Instantiate another new Bicycle + Bicycle octo = new Bicycle(5, 10); + Console.WriteLine("octo info: " + octo.ToString()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.ToString()); + + Console.Read(); + } // End main method + + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int _speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + internal int wheels; // Internal: Accessible from within the assembly + string name; // default: Only accessible from within this class + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + gear = 1; + cadence = 50; + _speed = 5; + name = "Bontrager"; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) + { + this.gear = startGear; + this.cadence = startCadence; + this._speed = startSpeed; + this.name = name; + this.hasCardsInSpokes = hasCardsInSpokes; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed) : + this(startCadence, startSpeed, 0, "big wheels", true) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties + + // Method declaration syntax: + // () + public int getCadence() + { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) + { + cadence = newValue; + } + + // virtual keyword indicates this method can be overridden + public virtual void setGear(int newValue) + { + gear = newValue; + } + + public void speedUp(int increment) + { + _speed += increment; + } + + public void slowDown(int decrement) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool hasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + private int _frameSize; + public int FrameSize + { + get { return _frameSize; } + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set { _frameSize = value; } + } + + //Method to display the attribute values of this Object. + public override string ToString() + { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + _speed + + " name: " + name + + " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true) + { + } + + public override void setGear(int gear) + { + gear = 0; + } + } +} // End Namespace + +``` + +## Topics Not Covered + + * Enums, Flags + * Attributes + * Generics (T), Delegates, Func, Actions, lambda expressions + * Exceptions, Interfaces, Abstraction + * LINQ + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + + + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/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) + * [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) -- cgit v1.2.3 From bf1f9d811cfc41c33cfeaabca68034ad531a097d Mon Sep 17 00:00:00 2001 From: Irfan Charania Date: Mon, 12 Aug 2013 18:04:11 -0700 Subject: Clean up namespace in C# --- csharp.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index d67f6c74..e079571e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -20,12 +20,10 @@ Multi-line comments look like this /// This is an XML documentation comment /// - +// Specify namespaces application will be using using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + // defines scope to organize code into "packages" namespace Learning -- cgit v1.2.3 From 93fc8f5e8044c404d1feb600cf50eb932b596325 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 10:10:49 -0700 Subject: Line length edits to C# --- csharp.html.markdown | 973 ++++++++++++++++++++++++++------------------------- 1 file changed, 487 insertions(+), 486 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index e079571e..c254b5a9 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -28,492 +28,493 @@ using System.Collections.Generic; // defines scope to organize code into "packages" namespace Learning { - // 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. - public class LearnCSharp - { - // A console application must have a main method as an entry point - public static void Main(string[] args) - { - // Use Console.WriteLine to print lines - Console.WriteLine("Hello World"); - Console.WriteLine( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // To print without a new line, use Console.Write - Console.Write("Hello "); - Console.Write("World"); - - - /////////////////////////////////////////////////// - // Types & Variables - // - // Declare a variable using - /////////////////////////////////////////////////// - - // Sbyte - Signed 8-bit integer - // (-128 <= sbyte <= 127) - sbyte fooSbyte = 100; - - // Byte - Unsigned 8-bit integer - // (0 <= byte <= 255) - byte fooByte = 100; - - // Short - Signed 16-bit integer - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Ushort - Unsigned 16-bit integer - // (0 <= ushort <= 65,535) - ushort fooUshort = 10000; - - // Integer - Signed 32-bit integer - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Uinteger - Unsigned 32-bit integer - // (0 <= uint <= 4,294,967,295) - uint fooUint = 1; - - // Long - Signed 64-bit integer - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L is used to denote that this variable value is of type long or ulong - // anything without is treated as int or uint depending on size. - - // Ulong - Unsigned 64-bit integer - // (0 <= ulong <= 18,446,744,073,709,551,615) - ulong fooUlong = 100000L; - - // Float - Single-precision 32-bit IEEE 754 Floating Point - // Precision: 7 digits - float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; - // otherwise it is treated as double. - - // Double - Double-precision 64-bit IEEE 754 Floating Point - // Precision: 15-16 digits - double fooDouble = 123.4; - - // Bool - true & false - bool fooBoolean = true; - bool barBoolean = false; - - // Char - A single 16-bit Unicode character - char fooChar = 'A'; - - // Strings - string fooString = "My string is here!"; - Console.WriteLine(fooString); - - // formatting - string fooFormattedString = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - Console.WriteLine(fooFormattedString); - - // formatting dates - DateTime fooDate = DateTime.Now; - Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - - // \n is an escaped character that starts a new line - string barString = "Printing on a new line?\nNo Problem!"; - Console.WriteLine(barString); - - // it can be written prettier by using the @ symbol - string bazString = @"Here's some stuff - on a new line!"; - Console.WriteLine(bazString); - - // quotes need to be escaped - // use \" normally - string quotedString = "some \"quoted\" stuff"; - Console.WriteLine(quotedString); - - // use "" when strings start with @ - string quotedString2 = @"some MORE ""quoted"" stuff"; - Console.WriteLine(quotedString2); - - // Use const or read-only to make a variable immutable - // const values are calculated at compile time - const int HOURS_I_WORK_PER_WEEK = 9001; - - // Nullable types - // any type can be made nullable by suffixing a ? - // ? = - int? nullable = null; - Console.WriteLine("Nullable variable: " + nullable); - - // ?? is syntactic sugar for specifying default value - // in case variable is null - int notNullable = nullable ?? 0; - Console.WriteLine("Not nullable variable: " + notNullable); - - // Var - compiler will choose the most appropriate type based on value - var fooImplicit = true; - - /////////////////////////////////////////////////// - // Data Structures - /////////////////////////////////////////////////// - Console.WriteLine("\n->Data Structures"); - - // Arrays - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; - int[] intArray = new int[10]; - string[] stringArray = new string[1]; - bool[] boolArray = new bool[100]; - - // Another way to declare & initialize an array - int[] y = { 9000, 1000, 1337 }; - - // Indexing an array - Accessing an element - Console.WriteLine("intArray @ 0: " + intArray[0]); - - // Arrays are zero-indexed and mutable. - intArray[1] = 1; - Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 - - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); - List intList = new List(); - List stringList = new List(); - - // Another way to declare & initialize a list - List z = new List { 9000, 1000, 1337 }; - - // Indexing a list - Accessing an element - // Lists are zero-indexed and mutable. - Console.WriteLine("z @ 0: " + z[2]); - - // Lists don't default to a value; - // A value must be added before accessing the index - intList.Add(1); - Console.WriteLine("intList @ 0: " + intList[0]); - - - // Others data structures to check out: - // - // Stack/Queue - // Dictionary - // Read-only Collections - // Tuple (.Net 4+) - - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - Console.WriteLine("\n->Operators"); - - int i1 = 1, i2 = 2; // Shorthand for multiple declarations - - // Arithmetic is straightforward - Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 - Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 - Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 - Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) - - // Modulo - Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - - // Comparison operators - Console.WriteLine("3 == 2? " + (3 == 2)); // => false - Console.WriteLine("3 != 2? " + (3 != 2)); // => true - Console.WriteLine("3 > 2? " + (3 > 2)); // => true - Console.WriteLine("3 < 2? " + (3 < 2)); // => false - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true - - // Bitwise operators! - /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR - */ - - // Incrementations - int i = 0; - Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //i = 1. Post-Incrementation - Console.WriteLine(++i); //i = 2. Pre-Incrementation - Console.WriteLine(i--); //i = 1. Post-Decrementation - Console.WriteLine(--i); //i = 0. Pre-Decrementation - - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - Console.WriteLine("\n->Control Structures"); - - // If statements are c-like - int j = 10; - if (j == 10) - { - Console.WriteLine("I get printed"); - } - else if (j > 10) - { - Console.WriteLine("I don't"); - } - else - { - Console.WriteLine("I also don't"); - } - - // Ternary operators - // A simple if/else can be written as follows - // ? : - string isTrue = (true) ? "True" : "False"; - Console.WriteLine("Ternary demo: " + isTrue); - - - // While loop - int fooWhile = 0; - while (fooWhile < 100) - { - //Console.WriteLine(fooWhile); - //Increment the counter - //Iterated 99 times, fooWhile 0->99 - fooWhile++; - } - Console.WriteLine("fooWhile Value: " + fooWhile); - - // Do While Loop - int fooDoWhile = 0; - do - { - //Console.WriteLine(fooDoWhile); - //Increment the counter - //Iterated 99 times, fooDoWhile 0->99 - fooDoWhile++; - } while (fooDoWhile < 100); - Console.WriteLine("fooDoWhile Value: " + fooDoWhile); - - // For Loop - int fooFor; - //for loop structure => for(; ; ) - for (fooFor = 0; fooFor < 10; fooFor++) - { - //Console.WriteLine(fooFor); - //Iterated 10 times, fooFor 0->9 - } - Console.WriteLine("fooFor Value: " + fooFor); - - // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. - int month = 3; - string monthString; - switch (month) - { - case 1: - monthString = "January"; - break; - case 2: - monthString = "February"; - break; - case 3: - monthString = "March"; - break; - default: - monthString = "Some other month"; - break; - } - Console.WriteLine("Switch Case Result: " + monthString); - - - /////////////////////////////////////// - // Converting Data Types And Typcasting - /////////////////////////////////////// - - // Converting data - - // Convert String To Integer - // this will throw an Exception on failure - int.Parse("123");//returns an integer version of "123" - - // try parse will default to type default on failure - // in this case: 0 - int tryInt; - int.TryParse("123", out tryInt); - - // Convert Integer To String - // Convert class has a number of methods to facilitate conversions - Convert.ToString(123); - - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - Console.WriteLine("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) - - // Use new to instantiate a class - Bicycle trek = new Bicycle(); - - // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); - - // ToString is a convention to display the value of this Object. - Console.WriteLine("trek info: " + trek.ToString()); - - // Instantiate another new Bicycle - Bicycle octo = new Bicycle(5, 10); - Console.WriteLine("octo info: " + octo.ToString()); - - // Instantiate a new Penny Farthing - PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("funbike info: " + funbike.ToString()); - - Console.Read(); - } // End main method - - - } // End LearnCSharp class - - // You can include other classes in a .cs file - - - // Class Declaration Syntax: - // class { - // //data fields, constructors, functions all inside. - // //functions are called as methods in Java. - // } - - public class Bicycle - { - // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int _speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - internal int wheels; // Internal: Accessible from within the assembly - string name; // default: Only accessible from within this class - - // readonly values are set at run time - // they can only be assigned upon declaration or in a constructor - readonly bool hasCardsInSpokes = false; // read-only private - - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle() - { - gear = 1; - cadence = 50; - _speed = 5; - name = "Bontrager"; - } - - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) - { - this.gear = startGear; - this.cadence = startCadence; - this._speed = startSpeed; - this.name = name; - this.hasCardsInSpokes = hasCardsInSpokes; - } - - // Constructors can be chained - public Bicycle(int startCadence, int startSpeed) : - this(startCadence, startSpeed, 0, "big wheels", true) - { - } - - // Function Syntax: - // () - - // classes can implement getters and setters for their fields - // or they can implement properties - - // Method declaration syntax: - // () - public int getCadence() - { - return cadence; - } - - // void methods require no return statement - public void setCadence(int newValue) - { - cadence = newValue; - } - - // virtual keyword indicates this method can be overridden - public virtual void setGear(int newValue) - { - gear = newValue; - } - - public void speedUp(int increment) - { - _speed += increment; - } - - public void slowDown(int decrement) - { - _speed -= decrement; - } - - // properties get/set values - // when only data needs to be accessed, consider using properties. - // properties may have either get or set, or both - private bool _hasTassles; // private variable - public bool hasTassles // public accessor - { - get { return _hasTassles; } - set { _hasTassles = value; } - } - - private int _frameSize; - public int FrameSize - { - get { return _frameSize; } - // you are able to specify access modifiers for either get or set - // this means only Bicycle class can call set on Framesize - private set { _frameSize = value; } - } - - //Method to display the attribute values of this Object. - public override string ToString() - { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + _speed + - " name: " + name + - " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + - "\n------------------------------\n" - ; - } - } // end class Bicycle - - // PennyFarthing is a subclass of Bicycle - class PennyFarthing : Bicycle - { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) - - // calling parent constructor - public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "PennyFarthing", true) - { - } - - public override void setGear(int gear) - { - gear = 0; - } - } + // 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. + public class LearnCSharp + { + // A console application must have a main method as an entry point + public static void Main(string[] args) + { + // Use Console.WriteLine to print lines + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // To print without a new line, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + + /////////////////////////////////////////////////// + // Types & Variables + // + // Declare a variable using + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - Signed 16-bit integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Ushort - Unsigned 16-bit integer + // (0 <= ushort <= 65,535) + ushort fooUshort = 10000; + + // Integer - Signed 32-bit integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Uinteger - Unsigned 32-bit integer + // (0 <= uint <= 4,294,967,295) + uint fooUint = 1; + + // Long - Signed 64-bit integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L is used to denote that this variable value is of type long or ulong + // anything without is treated as int or uint depending on size. + + // Ulong - Unsigned 64-bit integer + // (0 <= ulong <= 18,446,744,073,709,551,615) + ulong fooUlong = 100000L; + + // Float - Single-precision 32-bit IEEE 754 Floating Point + // Precision: 7 digits + float fooFloat = 234.5f; + // f is used to denote that this variable value is of type float; + // otherwise it is treated as double. + + // Double - Double-precision 64-bit IEEE 754 Floating Point + // Precision: 15-16 digits + double fooDouble = 123.4; + + // Bool - true & false + bool fooBoolean = true; + bool barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings + string fooString = "My string is here!"; + Console.WriteLine(fooString); + + // formatting + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + Console.WriteLine(fooFormattedString); + + // formatting dates + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // \n is an escaped character that starts a new line + string barString = "Printing on a new line?\nNo Problem!"; + Console.WriteLine(barString); + + // it can be written prettier by using the @ symbol + string bazString = @"Here's some stuff + on a new line!"; + Console.WriteLine(bazString); + + // quotes need to be escaped + // use \" normally + string quotedString = "some \"quoted\" stuff"; + Console.WriteLine(quotedString); + + // use "" when strings start with @ + string quotedString2 = @"some MORE ""quoted"" stuff"; + Console.WriteLine(quotedString2); + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + // Nullable types + // any type can be made nullable by suffixing a ? + // ? = + int? nullable = null; + Console.WriteLine("Nullable variable: " + nullable); + + // ?? is syntactic sugar for specifying default value + // in case variable is null + int notNullable = nullable ?? 0; + Console.WriteLine("Not nullable variable: " + notNullable); + + // Var - compiler will choose the most appropriate type based on value + var fooImplicit = true; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + Console.WriteLine("\n->Data Structures"); + + // Arrays + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + string[] stringArray = new string[1]; + bool[] boolArray = new bool[100]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + + // Arrays are zero-indexed and mutable. + intArray[1] = 1; + Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + + // Another way to declare & initialize a list + List z = new List { 9000, 1000, 1337 }; + + // Indexing a list - Accessing an element + // Lists are zero-indexed and mutable. + Console.WriteLine("z @ 0: " + z[2]); + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + + // Others data structures to check out: + // + // Stack/Queue + // Dictionary + // Read-only Collections + // Tuple (.Net 4+) + + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 + Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 + Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 + Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + Console.WriteLine("Ternary demo: " + isTrue); + + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Console.WriteLine(fooWhile); + //Increment the counter + //Iterated 99 times, fooWhile 0->99 + fooWhile++; + } + Console.WriteLine("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do + { + //Console.WriteLine(fooDoWhile); + //Increment the counter + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + Console.WriteLine("fooDoWhile Value: " + fooDoWhile); + + // For Loop + int fooFor; + //for loop structure => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) + { + //Console.WriteLine(fooFor); + //Iterated 10 times, fooFor 0->9 + } + Console.WriteLine("fooFor Value: " + fooFor); + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + default: + monthString = "Some other month"; + break; + } + Console.WriteLine("Switch Case Result: " + monthString); + + + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + int.TryParse("123", out tryInt); + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + Console.WriteLine("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.ToString()); + + // Instantiate another new Bicycle + Bicycle octo = new Bicycle(5, 10); + Console.WriteLine("octo info: " + octo.ToString()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.ToString()); + + Console.Read(); + } // End main method + + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int _speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + internal int wheels; // Internal: Accessible from within the assembly + string name; // default: Only accessible from within this class + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + gear = 1; + cadence = 50; + _speed = 5; + name = "Bontrager"; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes) + { + this.gear = startGear; + this.cadence = startCadence; + this._speed = startSpeed; + this.name = name; + this.hasCardsInSpokes = hasCardsInSpokes; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed) : + this(startCadence, startSpeed, 0, "big wheels", true) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties + + // Method declaration syntax: + // () + public int getCadence() + { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) + { + cadence = newValue; + } + + // virtual keyword indicates this method can be overridden + public virtual void setGear(int newValue) + { + gear = newValue; + } + + public void speedUp(int increment) + { + _speed += increment; + } + + public void slowDown(int decrement) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool hasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + private int _frameSize; + public int FrameSize + { + get { return _frameSize; } + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set { _frameSize = value; } + } + + //Method to display the attribute values of this Object. + public override string ToString() + { + return "gear: " + gear + + " cadence: " + cadence + + " speed: " + _speed + + " name: " + name + + " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true) + { + } + + public override void setGear(int gear) + { + gear = 0; + } + } } // End Namespace ``` -- cgit v1.2.3 From 2173dd419a1daa06efee295e3fe2cdbc40224433 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 15:57:52 +0200 Subject: Accessing nullable's value in C# --- csharp.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index c254b5a9..c9df6db9 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -144,6 +144,10 @@ namespace Learning int? nullable = null; Console.WriteLine("Nullable variable: " + nullable); + // In order to use nullable's value, you have to use Value property or to explicitly cast it + string? nullableString = "not null"; + Console.WriteLine("Nullable value is: " + nullableString.Value + " or: " + (string) nullableString ); + // ?? is syntactic sugar for specifying default value // in case variable is null int notNullable = nullable ?? 0; -- cgit v1.2.3 From 541fd3fb06bf6e97974123934ad89cb07a7ef289 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:01:08 +0200 Subject: C# Coding style: property names start with capitals --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index c9df6db9..490c34bb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -474,7 +474,7 @@ namespace Learning // when only data needs to be accessed, consider using properties. // properties may have either get or set, or both private bool _hasTassles; // private variable - public bool hasTassles // public accessor + public bool HasTassles // public accessor { get { return _hasTassles; } set { _hasTassles = value; } -- cgit v1.2.3 From 4295e85d6097e2d331ff75a958a3a5a064795410 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:03:35 +0200 Subject: C#: Auto-implemented properties --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 490c34bb..951958b6 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -480,13 +480,13 @@ namespace Learning set { _hasTassles = value; } } - private int _frameSize; + // Properties can be auto-implemented public int FrameSize { - get { return _frameSize; } + get; // you are able to specify access modifiers for either get or set // this means only Bicycle class can call set on Framesize - private set { _frameSize = value; } + private set; } //Method to display the attribute values of this Object. -- cgit v1.2.3 From c3df13db567b82fc0802e46c23e4e4486618b207 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 16:06:04 +0200 Subject: C#: comments about "this" keyword --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 951958b6..0cef8f05 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -422,10 +422,10 @@ namespace Learning public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes) { - this.gear = startGear; + this.gear = startGear; // "this" keyword denotes the current object this.cadence = startCadence; this._speed = startSpeed; - this.name = name; + this.name = name; // it can be useful when there's a name conflict this.hasCardsInSpokes = hasCardsInSpokes; } -- cgit v1.2.3 From 0312c061b292985a5d849253480b0a8e5eafb332 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:35:59 +0200 Subject: C#: Added myself to contributors list --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 0cef8f05..b113b6d3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,6 +3,7 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] filename: LearnCSharp.cs --- -- cgit v1.2.3 From b488745fc646b16df4ef87ddb746af596ea6588f Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:45:01 +0200 Subject: Static field --- csharp.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index b113b6d3..3de1eb66 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -403,7 +403,12 @@ namespace Learning private int _speed; // Private: Only accessible from within the class protected int gear; // Protected: Accessible from the class and subclasses internal int wheels; // Internal: Accessible from within the assembly - string name; // default: Only accessible from within this class + string name; // Everything is private by default: Only accessible from within this class + + // Static members belong to the type itself rather then specific object. + static public int bicyclesCreated = 0; + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); // readonly values are set at run time // they can only be assigned upon declaration or in a constructor @@ -417,6 +422,7 @@ namespace Learning cadence = 50; _speed = 5; name = "Bontrager"; + bicyclesCreated++; } // This is a specified constructor (it contains arguments) -- cgit v1.2.3 From 964476a6e859959a3c1ae6a005ba82ba0d6b234e Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:45:58 +0200 Subject: C#: Lacking static members --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 3de1eb66..584d40fd 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -535,6 +535,7 @@ namespace Learning * Enums, Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions + * Static properties, methods and classes * Exceptions, Interfaces, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) -- cgit v1.2.3 From bb1f4eb93a70882f959acf6e849a9663ad74deca Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 22:49:36 +0200 Subject: C#: edited example code according to Microsoft's naming conventions --- csharp.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 584d40fd..0740c3ed 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -450,29 +450,29 @@ namespace Learning // Method declaration syntax: // () - public int getCadence() + public int GetCadence() { return cadence; } // void methods require no return statement - public void setCadence(int newValue) + public void SetCadence(int newValue) { cadence = newValue; } // virtual keyword indicates this method can be overridden - public virtual void setGear(int newValue) + public virtual void SetGear(int newValue) { gear = newValue; } - public void speedUp(int increment) + public void SpeedUp(int increment) { _speed += increment; } - public void slowDown(int decrement) + public void SlowDown(int decrement) { _speed -= decrement; } @@ -521,7 +521,7 @@ namespace Learning { } - public override void setGear(int gear) + public override void SetGear(int gear) { gear = 0; } -- cgit v1.2.3 From ccdc21900d090a88ca02e25007f4e3c197b8f50e Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:08:24 +0200 Subject: C#: enums --- csharp.html.markdown | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 0740c3ed..fefcb0bb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -405,6 +405,19 @@ namespace Learning internal int wheels; // Internal: Accessible from within the assembly string name; // Everything is private by default: Only accessible from within this class + // Enum is a value type that consists of a set of named constants + public enum Brand + { + AIST, + BMC, + Electra, + Gitane + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public Brand brand; // After declaing an enum type, we can declare the field of this type + // Static members belong to the type itself rather then specific object. static public int bicyclesCreated = 0; // You can access them without a reference to any object: @@ -416,28 +429,30 @@ namespace Learning // Constructors are a way of creating classes // This is a default constructor - public Bicycle() + private Bicycle() { gear = 1; cadence = 50; _speed = 5; name = "Bontrager"; + brand = Brand.AIST; bicyclesCreated++; } // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes) + string name, bool hasCardsInSpokes, Brand brand) { this.gear = startGear; // "this" keyword denotes the current object this.cadence = startCadence; this._speed = startSpeed; this.name = name; // it can be useful when there's a name conflict this.hasCardsInSpokes = hasCardsInSpokes; + this.brand = brand; } // Constructors can be chained - public Bicycle(int startCadence, int startSpeed) : + public Bicycle(int startCadence, int startSpeed, Brand brand) : this(startCadence, startSpeed, 0, "big wheels", true) { } @@ -532,7 +547,7 @@ namespace Learning ## Topics Not Covered - * Enums, Flags + * Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties, methods and classes -- cgit v1.2.3 From dd1a6193605909f3d6abf7795cd18261b27696b9 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:09:07 +0200 Subject: C#: default parameter values --- csharp.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index fefcb0bb..599aaca3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -482,12 +482,13 @@ namespace Learning gear = newValue; } - public void SpeedUp(int increment) + // Method parameters can have defaut values. In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) { _speed += increment; } - public void SlowDown(int decrement) + public void SlowDown(int decrement = 1) { _speed -= decrement; } -- cgit v1.2.3 From 41ec7af8e5ac7e4a7ab8b8fc008466be98b0cdc4 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:09:21 +0200 Subject: Static methods --- csharp.html.markdown | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 599aaca3..22fb58e1 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -523,6 +523,14 @@ namespace Learning "\n------------------------------\n" ; } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class memebers + return bicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + } // end class Bicycle // PennyFarthing is a subclass of Bicycle @@ -551,7 +559,7 @@ namespace Learning * Flags * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions - * Static properties, methods and classes + * Static properties * Exceptions, Interfaces, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) -- cgit v1.2.3 From cae70d430e40478e2c916489e53ffcb24f8fe024 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:28:21 +0200 Subject: C#: calling base method --- csharp.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 22fb58e1..0012fcb3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -549,6 +549,13 @@ namespace Learning { gear = 0; } + + public override string ToString() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return reuslt; + } } } // End Namespace -- cgit v1.2.3 From a225349acb165084a9da95f2da631a7525c513d3 Mon Sep 17 00:00:00 2001 From: Max Yankov Date: Sat, 17 Aug 2013 23:28:55 +0200 Subject: C#: interfaces --- csharp.html.markdown | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 0012fcb3..55de415d 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -557,6 +557,36 @@ namespace Learning return reuslt; } } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods, fields & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public void Broken + { + get + { + return damage > 100; + } + } + } } // End Namespace ``` @@ -567,7 +597,7 @@ namespace Learning * Attributes * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties - * Exceptions, Interfaces, Abstraction + * Exceptions, Abstraction * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms -- cgit v1.2.3 From 1dd0e00f2249526520b047c6852d22a7ee2df7ad Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 13 Sep 2013 10:28:48 -0700 Subject: Fixed a bunch of headers --- csharp.html.markdown | 2 -- 1 file changed, 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 55de415d..d3adbd01 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1,11 +1,9 @@ --- - language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] filename: LearnCSharp.cs - --- C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. -- cgit v1.2.3 From fceaa4a7cf0bcca54306ce6994f273f6b3710290 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:05:14 -0400 Subject: added Decimal type example for C# --- csharp.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index d3adbd01..bb36d6ce 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -95,8 +95,12 @@ namespace Learning // Double - Double-precision 64-bit IEEE 754 Floating Point // Precision: 15-16 digits double fooDouble = 123.4; + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; - // Bool - true & false + // Boolean - true & false bool fooBoolean = true; bool barBoolean = false; -- cgit v1.2.3 From 81c0480780a600ef27071285e002e8ea78dc727c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:23:24 -0400 Subject: corrected errors about the nullable types for C# --- csharp.html.markdown | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index bb36d6ce..16e3749e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -107,7 +107,8 @@ namespace Learning // Char - A single 16-bit Unicode character char fooChar = 'A'; - // Strings + // Strings -- unlike the previous base types which are all value types, + // a string is a reference type. That is, you can set it to null string fooString = "My string is here!"; Console.WriteLine(fooString); @@ -142,14 +143,21 @@ namespace Learning const int HOURS_I_WORK_PER_WEEK = 9001; // Nullable types - // any type can be made nullable by suffixing a ? + // any value type (i.e. not a class) can be made nullable by suffixing a ? // ? = int? nullable = null; Console.WriteLine("Nullable variable: " + nullable); - // In order to use nullable's value, you have to use Value property or to explicitly cast it - string? nullableString = "not null"; - Console.WriteLine("Nullable value is: " + nullableString.Value + " or: " + (string) nullableString ); + // In order to use nullable's value, you have to use Value property + // or to explicitly cast it + DateTime? nullableDate = null; + // The previous line would not have compiled without the '?' + // because DateTime is a value type + // ? is equivalent to writing Nullable + Nullable otherNullableDate = nullableDate; + + nullableDate = DateTime.Now; + Console.WriteLine("Nullable value is: " + nullableDate.Value + " or: " + (DateTime) nullableDate ); // ?? is syntactic sugar for specifying default value // in case variable is null -- cgit v1.2.3 From a2b14fcedfaa01d6dea7d7682b82fc5ddae9b84d Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:27:55 -0400 Subject: mentioned strings immutability and added details about var keyword (C#) --- csharp.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 16e3749e..c6394974 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -111,6 +111,9 @@ namespace Learning // a string is a reference type. That is, you can set it to null string fooString = "My string is here!"; Console.WriteLine(fooString); + // You can access each character of the string with an indexer: + char charFromString = fooString[1]; // 'y' + // Strings are immutable: you can't do fooString[1] = 'X'; // formatting string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); @@ -165,6 +168,8 @@ namespace Learning Console.WriteLine("Not nullable variable: " + notNullable); // Var - compiler will choose the most appropriate type based on value + // Please not that this does not remove type safety. + // In this case, the type of fooImplicit is known to be a bool at compile time var fooImplicit = true; /////////////////////////////////////////////////// -- cgit v1.2.3 From dbfaa5ba52758cc826e710024f0be22404817e5c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:29:03 -0400 Subject: typo (not instead of note) for C# doc --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index c6394974..2854a49b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -168,7 +168,7 @@ namespace Learning Console.WriteLine("Not nullable variable: " + notNullable); // Var - compiler will choose the most appropriate type based on value - // Please not that this does not remove type safety. + // Please note that this does not remove type safety. // In this case, the type of fooImplicit is known to be a bool at compile time var fooImplicit = true; -- cgit v1.2.3 From 41cf74fa53b1d315e2909e1ea62f4874727b578a Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:33:11 -0400 Subject: corrections for C# doc --- csharp.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 2854a49b..7239ca52 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -218,7 +218,7 @@ namespace Learning // Others data structures to check out: // // Stack/Queue - // Dictionary + // Dictionary (an implementation of a hash map) // Read-only Collections // Tuple (.Net 4+) @@ -252,7 +252,6 @@ namespace Learning ~ Unary bitwise complement << Signed left shift >> Signed right shift - >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR -- cgit v1.2.3 From 67b9af44925a66ac0dc278050bcaaa80fd50f21c Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:39:59 -0400 Subject: added details for the switch statement for C# --- csharp.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 7239ca52..dcbb30d1 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -343,6 +343,14 @@ namespace Learning case 3: monthString = "March"; break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; default: monthString = "Some other month"; break; -- cgit v1.2.3 From 3b5e4837bda104ca6e23b65327f819953d1c1b2e Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 15:49:20 -0400 Subject: more details for the enums (C#) --- csharp.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index dcbb30d1..76af24af 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -359,7 +359,7 @@ namespace Learning /////////////////////////////////////// - // Converting Data Types And Typcasting + // Converting Data Types And Typecasting /////////////////////////////////////// // Converting data @@ -413,7 +413,7 @@ namespace Learning // Class Declaration Syntax: - // class { + // class { // //data fields, constructors, functions all inside. // //functions are called as methods in Java. // } @@ -428,11 +428,14 @@ namespace Learning string name; // Everything is private by default: Only accessible from within this class // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. public enum Brand { AIST, BMC, - Electra, + Electra=42, //you can explicitly set a value to a name Gitane } // We defined this type inside a Bicycle class, so it is a nested type -- cgit v1.2.3 From 10bb7dbce413be31916c02b340b15f1a4e4a6a23 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:00:08 -0400 Subject: various typos + added an example to declare an auto property (C#) --- csharp.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 76af24af..0c459bdb 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -441,7 +441,7 @@ namespace Learning // We defined this type inside a Bicycle class, so it is a nested type // Code outside of this class should reference this type as Bicycle.Brand - public Brand brand; // After declaing an enum type, we can declare the field of this type + public Brand brand; // After declaring an enum type, we can declare the field of this type // Static members belong to the type itself rather then specific object. static public int bicyclesCreated = 0; @@ -486,7 +486,7 @@ namespace Learning // () // classes can implement getters and setters for their fields - // or they can implement properties + // or they can implement properties (this is the preferred way in C#) // Method declaration syntax: // () @@ -501,13 +501,13 @@ namespace Learning cadence = newValue; } - // virtual keyword indicates this method can be overridden + // virtual keyword indicates this method can be overridden in a derived class public virtual void SetGear(int newValue) { gear = newValue; } - // Method parameters can have defaut values. In this case, methods can be called with these parameters omitted + // Method parameters can have default values. In this case, methods can be called with these parameters omitted public void SpeedUp(int increment = 1) { _speed += increment; @@ -527,6 +527,11 @@ namespace Learning get { return _hasTassles; } set { _hasTassles = value; } } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) to restrict its access: + public bool IsBroken { get; private set; } // Properties can be auto-implemented public int FrameSize @@ -552,7 +557,7 @@ namespace Learning // Methods can also be static. It can be useful for helper methods public static bool DidWeCreateEnoughBycles() { - // Within a static method, we only can reference static class memebers + // Within a static method, we only can reference static class members return bicyclesCreated > 9000; } // If your class only needs static members, consider marking the class itself as static. @@ -591,7 +596,7 @@ namespace Learning interface IBreakable { - bool Broken { get; } // interfaces can contain properties as well as methods, fields & events + bool Broken { get; } // interfaces can contain properties as well as methods & events } // Class can inherit only one other class, but can implement any amount of interfaces -- cgit v1.2.3 From 758cd94b33dcfce89ab308c67725513184fb3c4b Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:07:43 -0400 Subject: added an example for the foreach loop in C# --- csharp.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 0c459bdb..e6a174c3 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -324,6 +324,17 @@ namespace Learning //Iterated 10 times, fooFor 0->9 } Console.WriteLine("fooFor Value: " + fooFor); + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework implement one or both of these interfaces + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Console.WriteLine(character); + //Iterated over all the characters in the string + } // Switch Case // A switch works with the byte, short, char, and int data types. -- cgit v1.2.3 From 71a62e642d2f31dcdc62aee9fd61ca6fa18d1c57 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:11:45 -0400 Subject: breaking some lines (C#) --- csharp.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index e6a174c3..8b293534 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -328,7 +328,8 @@ namespace Learning // For Each Loop // foreach loop structure => foreach( in ) // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework implement one or both of these interfaces + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. // (The ToCharArray() could be removed, because a string also implements IEnumerable) foreach (char character in "Hello World".ToCharArray()) { @@ -518,7 +519,8 @@ namespace Learning gear = newValue; } - // Method parameters can have default values. In this case, methods can be called with these parameters omitted + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted public void SpeedUp(int increment = 1) { _speed += increment; @@ -541,7 +543,8 @@ namespace Learning // You can also define an automatic property in one line // this syntax will create a backing field automatically. - // You can set an access modifier on either the getter or the setter (or both) to restrict its access: + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: public bool IsBroken { get; private set; } // Properties can be auto-implemented -- cgit v1.2.3 From 6d5509e94b7e752e11285a86a2fe8f7f72e9f600 Mon Sep 17 00:00:00 2001 From: Melvyn Date: Sat, 21 Sep 2013 16:16:04 -0400 Subject: added myself to the contributors (C#) --- csharp.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 8b293534..1471b833 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,6 +3,7 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] filename: LearnCSharp.cs --- -- cgit v1.2.3 From 0cee5bd79af4deefe246dde09cdfcd44dca80558 Mon Sep 17 00:00:00 2001 From: Shaun McCarthy Date: Sat, 26 Oct 2013 14:34:39 -0400 Subject: Added Interesting Features (and fixed / cleaned up other code) Fixed syntax errors, made items more succinct, and added a section of interesting features in c# --- csharp.html.markdown | 583 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 354 insertions(+), 229 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 1471b833..f4c30b03 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,8 +3,8 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] -filename: LearnCSharp.cs + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] --- C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. @@ -23,7 +23,12 @@ Multi-line comments look like this // Specify namespaces application will be using using System; using System.Collections.Generic; - +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; // defines scope to organize code into "packages" namespace Learning @@ -32,8 +37,8 @@ namespace Learning // you're allowed to do otherwise, but shouldn't for sanity. public class LearnCSharp { - // A console application must have a main method as an entry point - public static void Main(string[] args) + // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before + public static void Syntax() { // Use Console.WriteLine to print lines Console.WriteLine("Hello World"); @@ -46,7 +51,6 @@ namespace Learning Console.Write("Hello "); Console.Write("World"); - /////////////////////////////////////////////////// // Types & Variables // @@ -61,140 +65,83 @@ namespace Learning // (0 <= byte <= 255) byte fooByte = 100; - // Short - Signed 16-bit integer - // (-32,768 <= short <= 32,767) + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) short fooShort = 10000; - - // Ushort - Unsigned 16-bit integer - // (0 <= ushort <= 65,535) ushort fooUshort = 10000; - // Integer - Signed 32-bit integer - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) - // Uinteger - Unsigned 32-bit integer - // (0 <= uint <= 4,294,967,295) - uint fooUint = 1; - - // Long - Signed 64-bit integer - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. // L is used to denote that this variable value is of type long or ulong - // anything without is treated as int or uint depending on size. - // Ulong - Unsigned 64-bit integer - // (0 <= ulong <= 18,446,744,073,709,551,615) - ulong fooUlong = 100000L; + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits // Float - Single-precision 32-bit IEEE 754 Floating Point - // Precision: 7 digits - float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; - // otherwise it is treated as double. + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float - // Double - Double-precision 64-bit IEEE 754 Floating Point - // Precision: 15-16 digits - double fooDouble = 123.4; - - // Decimal - a 128-bits data type, with more precision than other floating-point types, - // suited for financial and monetary calculations - decimal fooDecimal = 150.3m; + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; // Boolean - true & false - bool fooBoolean = true; - bool barBoolean = false; + bool fooBoolean = true; // or false // Char - A single 16-bit Unicode character char fooChar = 'A'; // Strings -- unlike the previous base types which are all value types, - // a string is a reference type. That is, you can set it to null - string fooString = "My string is here!"; + // a string is a reference type. That is, you can set it to null + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; Console.WriteLine(fooString); - // You can access each character of the string with an indexer: - char charFromString = fooString[1]; // 'y' - // Strings are immutable: you can't do fooString[1] = 'X'; - // formatting + // You can access each character of the string with an indexer: + char charFromString = fooString[1]; // 'y' + // Strings are immutable: you can't do fooString[1] = 'X'; + + // Compare strings with current culture, ignoring case + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatting, based on sprintf string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - Console.WriteLine(fooFormattedString); - // formatting dates + // Dates & Formatting DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // \n is an escaped character that starts a new line - string barString = "Printing on a new line?\nNo Problem!"; - Console.WriteLine(barString); - - // it can be written prettier by using the @ symbol + // You can split a string over two lines with the @ symbol. To escape " use "" string bazString = @"Here's some stuff - on a new line!"; - Console.WriteLine(bazString); - - // quotes need to be escaped - // use \" normally - string quotedString = "some \"quoted\" stuff"; - Console.WriteLine(quotedString); - - // use "" when strings start with @ - string quotedString2 = @"some MORE ""quoted"" stuff"; - Console.WriteLine(quotedString2); +on a new line! ""Wow!"", the masses cried"; // Use const or read-only to make a variable immutable // const values are calculated at compile time const int HOURS_I_WORK_PER_WEEK = 9001; - // Nullable types - // any value type (i.e. not a class) can be made nullable by suffixing a ? - // ? = - int? nullable = null; - Console.WriteLine("Nullable variable: " + nullable); - - // In order to use nullable's value, you have to use Value property - // or to explicitly cast it - DateTime? nullableDate = null; - // The previous line would not have compiled without the '?' - // because DateTime is a value type - // ? is equivalent to writing Nullable - Nullable otherNullableDate = nullableDate; - - nullableDate = DateTime.Now; - Console.WriteLine("Nullable value is: " + nullableDate.Value + " or: " + (DateTime) nullableDate ); - - // ?? is syntactic sugar for specifying default value - // in case variable is null - int notNullable = nullable ?? 0; - Console.WriteLine("Not nullable variable: " + notNullable); - - // Var - compiler will choose the most appropriate type based on value - // Please note that this does not remove type safety. - // In this case, the type of fooImplicit is known to be a bool at compile time - var fooImplicit = true; - /////////////////////////////////////////////////// // Data Structures /////////////////////////////////////////////////// - Console.WriteLine("\n->Data Structures"); - // Arrays + // Arrays - zero indexed // The array size must be decided upon declaration // The format for declaring an array is follows: // [] = new []; int[] intArray = new int[10]; - string[] stringArray = new string[1]; - bool[] boolArray = new bool[100]; // Another way to declare & initialize an array int[] y = { 9000, 1000, 1337 }; // Indexing an array - Accessing an element Console.WriteLine("intArray @ 0: " + intArray[0]); - - // Arrays are zero-indexed and mutable. + // Arrays are mutable. intArray[1] = 1; - Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1 // Lists // Lists are used more frequently than arrays as they are more flexible @@ -202,28 +149,21 @@ namespace Learning // List = new List(); List intList = new List(); List stringList = new List(); - - // Another way to declare & initialize a list - List z = new List { 9000, 1000, 1337 }; - - // Indexing a list - Accessing an element - // Lists are zero-indexed and mutable. - Console.WriteLine("z @ 0: " + z[2]); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for templates - Check out the cool stuff section // Lists don't default to a value; // A value must be added before accessing the index intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // // Stack/Queue // Dictionary (an implementation of a hash map) + // HashSet // Read-only Collections // Tuple (.Net 4+) - /////////////////////////////////////// // Operators /////////////////////////////////////// @@ -232,10 +172,7 @@ namespace Learning int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward - Console.WriteLine("1+2 = " + (i1 + i2)); // => 3 - Console.WriteLine("2-1 = " + (i2 - i1)); // => 1 - Console.WriteLine("2*1 = " + (i2 * i1)); // => 2 - Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 @@ -266,7 +203,6 @@ namespace Learning Console.WriteLine(i--); //i = 1. Post-Decrementation Console.WriteLine(--i); //i = 0. Pre-Decrementation - /////////////////////////////////////// // Control Structures /////////////////////////////////////// @@ -291,50 +227,37 @@ namespace Learning // A simple if/else can be written as follows // ? : string isTrue = (true) ? "True" : "False"; - Console.WriteLine("Ternary demo: " + isTrue); - // While loop int fooWhile = 0; while (fooWhile < 100) { - //Console.WriteLine(fooWhile); - //Increment the counter //Iterated 99 times, fooWhile 0->99 fooWhile++; } - Console.WriteLine("fooWhile Value: " + fooWhile); // Do While Loop int fooDoWhile = 0; do { - //Console.WriteLine(fooDoWhile); - //Increment the counter //Iterated 99 times, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); - Console.WriteLine("fooDoWhile Value: " + fooDoWhile); - // For Loop - int fooFor; //for loop structure => for(; ; ) - for (fooFor = 0; fooFor < 10; fooFor++) + for (int fooFor = 0; fooFor < 10; fooFor++) { - //Console.WriteLine(fooFor); //Iterated 10 times, fooFor 0->9 } - Console.WriteLine("fooFor Value: " + fooFor); - - // For Each Loop + + // For Each Loop // foreach loop structure => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework - // implement one or both of these interfaces. - // (The ToCharArray() could be removed, because a string also implements IEnumerable) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) foreach (char character in "Hello World".ToCharArray()) { - //Console.WriteLine(character); //Iterated over all the characters in the string } @@ -356,20 +279,18 @@ namespace Learning case 3: monthString = "March"; break; - // You can assign more than one case to an action - // But you can't add an action without a break before another case - // (if you want to do this, you would have to explicitly add a goto case x - case 6: - case 7: - case 8: - monthString = "Summer time!!"; - break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; default: monthString = "Some other month"; break; } - Console.WriteLine("Switch Case Result: " + monthString); - /////////////////////////////////////// // Converting Data Types And Typecasting @@ -384,46 +305,227 @@ namespace Learning // try parse will default to type default on failure // in this case: 0 int tryInt; - int.TryParse("123", out tryInt); + if (int.TryParse("123", out tryInt)) // Funciton is boolean + Console.WriteLine(tryInt); // 123 // Convert Integer To String // Convert class has a number of methods to facilitate conversions Convert.ToString(123); + // or + tryInt.ToString(); + } - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - Console.WriteLine("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file // Use new to instantiate a class Bicycle trek = new Bicycle(); // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; // ToString is a convention to display the value of this Object. - Console.WriteLine("trek info: " + trek.ToString()); - - // Instantiate another new Bicycle - Bicycle octo = new Bicycle(5, 10); - Console.WriteLine("octo info: " + octo.ToString()); + Console.WriteLine("trek info: " + trek.Info()); // Instantiate a new Penny Farthing PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("funbike info: " + funbike.ToString()); + Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); } // End main method + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + public static void MethodSignature(string maxCount) + { + } + + // TEMPLATES + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // TEMPLATES + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a template above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRespository(); + + // execution is delayed, which is great when querying a database + var fitler = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + fitler = fitler.Where(b => b.IsBroken); // no query run + + var query = fitler + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } } // End LearnCSharp class // You can include other classes in a .cs file + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } // Class Declaration Syntax: // class { @@ -434,64 +536,88 @@ namespace Learning public class Bicycle { // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int _speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - internal int wheels; // Internal: Accessible from within the assembly - string name; // Everything is private by default: Only accessible from within this class + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword privatee + public string Name { get; set; } // Enum is a value type that consists of a set of named constants - // It is really just mapping a name to a value (an int, unless specified otherwise). - // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. - // An enum can't contain the same value twice. - public enum Brand + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand { AIST, BMC, - Electra=42, //you can explicitly set a value to a name + Electra = 42, //you can explicitly set a value to a name Gitane } // We defined this type inside a Bicycle class, so it is a nested type // Code outside of this class should reference this type as Bicycle.Brand - public Brand 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 // Static members belong to the type itself rather then specific object. - static public int bicyclesCreated = 0; // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; // readonly values are set at run time // they can only be assigned upon declaration or in a constructor - readonly bool hasCardsInSpokes = false; // read-only private + readonly bool _hasCardsInSpokes = false; // read-only private // Constructors are a way of creating classes // This is a default constructor - private Bicycle() + public Bicycle() { - gear = 1; - cadence = 50; + this.Gear = 1; // you can access mmebers of the object with the keyword this + Cadence = 50; // but you don't always need it _speed = 5; - name = "Bontrager"; - brand = Brand.AIST; - bicyclesCreated++; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; } // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, Brand brand) + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first { - this.gear = startGear; // "this" keyword denotes the current object - this.cadence = startCadence; - this._speed = startSpeed; - this.name = name; // it can be useful when there's a name conflict - this.hasCardsInSpokes = hasCardsInSpokes; - this.brand = brand; + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; } // Constructors can be chained - public Bicycle(int startCadence, int startSpeed, Brand brand) : - this(startCadence, startSpeed, 0, "big wheels", true) + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) { } @@ -501,27 +627,8 @@ namespace Learning // classes can implement getters and setters for their fields // or they can implement properties (this is the preferred way in C#) - // Method declaration syntax: - // () - public int GetCadence() - { - return cadence; - } - - // void methods require no return statement - public void SetCadence(int newValue) - { - cadence = newValue; - } - - // virtual keyword indicates this method can be overridden in a derived class - public virtual void SetGear(int newValue) - { - gear = newValue; - } - // Method parameters can have default values. - // In this case, methods can be called with these parameters omitted + // In this case, methods can be called with these parameters omitted public void SpeedUp(int increment = 1) { _speed += increment; @@ -541,12 +648,12 @@ namespace Learning get { return _hasTassles; } set { _hasTassles = value; } } - - // You can also define an automatic property in one line - // this syntax will create a backing field automatically. - // You can set an access modifier on either the getter or the setter (or both) - // to restrict its access: - public bool IsBroken { get; private set; } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } // Properties can be auto-implemented public int FrameSize @@ -558,13 +665,13 @@ namespace Learning } //Method to display the attribute values of this Object. - public override string ToString() + public virtual string Info() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + _speed + - " name: " + name + - " cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") + + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + "\n------------------------------\n" ; } @@ -573,9 +680,10 @@ namespace Learning public static bool DidWeCreateEnoughBycles() { // Within a static method, we only can reference static class members - return bicyclesCreated > 9000; + return BicyclesCreated > 9000; } // If your class only needs static members, consider marking the class itself as static. + } // end class Bicycle // PennyFarthing is a subclass of Bicycle @@ -586,20 +694,27 @@ namespace Learning // calling parent constructor public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "PennyFarthing", true) + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { } - public override void SetGear(int gear) + protected override int Gear { - gear = 0; + get + { + return 0; + } + set + { + throw new ArgumentException("You can't change gears on a PennyFarthing"); + } } - public override string ToString() + public override string Info() { string result = "PennyFarthing bicycle "; result += base.ToString(); // Calling the base version of the method - return reuslt; + return result; } } @@ -624,7 +739,7 @@ namespace Learning damage += meters; } - public void Broken + public bool Broken { get { @@ -632,24 +747,34 @@ namespace Learning } } } -} // End Namespace + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRespository : DbSet + { + public BikeRespository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace ``` ## Topics Not Covered * Flags * Attributes - * Generics (T), Delegates, Func, Actions, lambda expressions * Static properties * Exceptions, Abstraction - * LINQ * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms * Windows Presentation Foundation (WPF) - - ## Further Reading * [DotNetPerls](http://www.dotnetperls.com) -- cgit v1.2.3 From eccc9e094832350842f16f3a7666aa633748098b Mon Sep 17 00:00:00 2001 From: Shaun McCarthy Date: Sat, 26 Oct 2013 15:27:53 -0400 Subject: Reanmed to Generics instead of templates --- csharp.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index f4c30b03..8c15b86f 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -150,7 +150,7 @@ on a new line! ""Wow!"", the masses cried"; List intList = new List(); List stringList = new List(); List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for templates - Check out the cool stuff section + // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; // A value must be added before accessing the index @@ -369,7 +369,7 @@ on a new line! ""Wow!"", the masses cried"; { } - // TEMPLATES + // GENERICS // The classes for TKey and TValue is specified by the user calling this function. // This method emulates the SetDefault of Python public static TValue SetDefault( @@ -417,12 +417,13 @@ on a new line! ""Wow!"", the masses cried"; var magic = "magic is a string, at compile time, so you still get type safety"; // magic = 9; will not work as magic is a string, not an int - // TEMPLATES + // GENERICS + // var phonebook = new Dictionary() { {"Sarah", "212 555 5555"} // Add some entries to the phone book }; - // Calling SETDEFAULT defined as a template above + // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly -- cgit v1.2.3 From 7ff3de74fe941a220e6fb3e3e3434d90d0d51cc6 Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 27 Oct 2013 22:17:56 -0700 Subject: Updates --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 1471b833..ccc0ffad 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -3,7 +3,7 @@ language: c# contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] + - ["Melvyn Laïly", "http://x2a.yt"] filename: LearnCSharp.cs --- -- cgit v1.2.3 From fbb7ea38a1530d2e4cca6bce7f3db6b392e90ce1 Mon Sep 17 00:00:00 2001 From: mvalipour Date: Mon, 18 Nov 2013 22:58:27 +0000 Subject: Fix while loop iterator incorrect count The while loop is repeated 100 times not 99 times. 0~99 inclusive. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 87c2f704..dad0c26b 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -233,7 +233,7 @@ on a new line! ""Wow!"", the masses cried"; int fooWhile = 0; while (fooWhile < 100) { - //Iterated 99 times, fooWhile 0->99 + //Iterated 100 times, fooWhile 0->99 fooWhile++; } -- cgit v1.2.3 From 00338a1a61040b70ec3e068f69ccfad31aa1934d Mon Sep 17 00:00:00 2001 From: olwaro Date: Sun, 16 Feb 2014 14:24:33 +0100 Subject: Fix some misleading comments --- csharp.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index dad0c26b..3a870b7a 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -105,7 +105,7 @@ namespace Learning Console.WriteLine(fooString); // You can access each character of the string with an indexer: - char charFromString = fooString[1]; // 'y' + char charFromString = fooString[1]; // => 'e' // Strings are immutable: you can't do fooString[1] = 'X'; // Compare strings with current culture, ignoring case @@ -173,7 +173,7 @@ on a new line! ""Wow!"", the masses cried"; int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward - Console.WriteLine(i1 + i2 - i1 * 3 / 7); // + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 @@ -241,7 +241,7 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //Iterated 99 times, fooDoWhile 0->99 + //Iterated 100 times, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); @@ -576,7 +576,7 @@ on a new line! ""Wow!"", the masses cried"; AIST, BMC, Electra = 42, //you can explicitly set a value to a name - Gitane + Gitane // 43 } // We defined this type inside a Bicycle class, so it is a nested type // Code outside of this class should reference this type as Bicycle.Brand -- cgit v1.2.3 From 8b62c313b1e95428adb363425d35456e726e2d7f Mon Sep 17 00:00:00 2001 From: olwaro Date: Sun, 16 Feb 2014 22:00:33 +0100 Subject: Adds an example of 'using' statement --- csharp.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index dad0c26b..e240bf86 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -30,6 +30,7 @@ using System.Linq; using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; +using System.IO; // defines scope to organize code into "packages" namespace Learning @@ -434,6 +435,17 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 + // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, ressources will be released. + // Even if an exception is thrown. + } + // PARALLEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx var websites = new string[] { -- cgit v1.2.3 From f6032ba1906f51a59ecc17d24864a6f56d100c14 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 17 Feb 2014 10:43:18 +0100 Subject: Fixes typos --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index e240bf86..12bdf168 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -435,14 +435,14 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily + // DISPOSABLE RESSOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); - // At the end of scope, ressources will be released. + // At the end of scope, resources will be released. // Even if an exception is thrown. } -- cgit v1.2.3 From 7350deb1035369453c0651ecd81c4e00cae04142 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 24 Feb 2014 19:54:54 +0100 Subject: Adds loan pattern example to french translation. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 81b50e08..a5b2e1c2 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -435,7 +435,7 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESSOURCES 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.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. -- cgit v1.2.3 From 9d7566d82edf776b5f52ec397cd06f8e24e54b86 Mon Sep 17 00:00:00 2001 From: olwaro Date: Mon, 24 Feb 2014 21:39:05 +0100 Subject: Fix what Nami-Doc spotted. --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index a5b2e1c2..a689fe97 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -511,11 +511,11 @@ on a new line! ""Wow!"", the masses cried"; var db = new BikeRespository(); // execution is delayed, which is great when querying a database - var fitler = db.Bikes.Where(b => b.HasTassles); // no query run + var filter = db.Bikes.Where(b => b.HasTassles); // no query run if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality - fitler = fitler.Where(b => b.IsBroken); // no query run + filter = filter.Where(b => b.IsBroken); // no query run - var query = fitler + var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) .Select(b => b.Name); // still no query run -- cgit v1.2.3 From 0622062e2a42069af92b549d9774addb4ffc1f0a Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Thu, 20 Mar 2014 18:01:56 +0800 Subject: csharp: typos combine #574 #575 #576 to one pr --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index a689fe97..81eb467d 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -558,7 +558,7 @@ on a new line! ""Wow!"", the masses cried"; } set // set - define a method to set a proprety { - _cadence = value; // Value is the value passed in to to the setter + _cadence = value; // Value is the value passed in to the setter } } private int _cadence; @@ -576,7 +576,7 @@ on a new line! ""Wow!"", the masses cried"; } int _speed; // Everything is private by default: Only accessible from within this class. - // can also use keyword privatee + // can also use keyword private public string Name { get; set; } // Enum is a value type that consists of a set of named constants @@ -608,7 +608,7 @@ on a new line! ""Wow!"", the masses cried"; // This is a default constructor public Bicycle() { - this.Gear = 1; // you can access mmebers of the object with the keyword this + this.Gear = 1; // you can access members of the object with the keyword this Cadence = 50; // but you don't always need it _speed = 5; Name = "Bontrager"; -- cgit v1.2.3 From 4e6a111b6f08b8a11ccdf2cf236a48d50eefb1f4 Mon Sep 17 00:00:00 2001 From: discomethod Date: Mon, 26 May 2014 18:16:11 +0100 Subject: minor typo --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 81eb467d..4fa8deba 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -307,7 +307,7 @@ on a new line! ""Wow!"", the masses cried"; // try parse will default to type default on failure // in this case: 0 int tryInt; - if (int.TryParse("123", out tryInt)) // Funciton is boolean + if (int.TryParse("123", out tryInt)) // Function is boolean Console.WriteLine(tryInt); // 123 // Convert Integer To String -- cgit v1.2.3 From 7401ef2411e19d073685a09a668c9aa3a31081f6 Mon Sep 17 00:00:00 2001 From: Adhithya R Date: Mon, 7 Jul 2014 16:38:17 +0530 Subject: MethodSignature -> MethodSignatures Possible typo. Text mentions method names being the same but they weren't. Corrected. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 4fa8deba..136f6c50 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -367,7 +367,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can have the same name, as long as the signature is unique - public static void MethodSignature(string maxCount) + public static void MethodSignatures(string maxCount) { } -- cgit v1.2.3 From 6ce6aa7b548151371bcc31f00925aa890a4356e7 Mon Sep 17 00:00:00 2001 From: m90 Date: Tue, 7 Oct 2014 20:38:14 +0200 Subject: fix typo -> re(s)pository pattern --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 136f6c50..f6708590 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -508,7 +508,7 @@ on a new line! ""Wow!"", the masses cried"; // LINQ - maps a store to IQueryable objects, with delayed execution // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document - var db = new BikeRespository(); + var db = new BikeRepository(); // execution is delayed, which is great when querying a database var filter = db.Bikes.Where(b => b.HasTassles); // no query run @@ -767,9 +767,9 @@ on a new line! ""Wow!"", the masses cried"; /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// - public class BikeRespository : DbSet + public class BikeRepository : DbSet { - public BikeRespository() + public BikeRepository() : base() { } -- cgit v1.2.3 From 9a8d8f0e5da4af6ddf18124f2cc203dcf57b52e5 Mon Sep 17 00:00:00 2001 From: Adrian Cooney Date: Wed, 10 Dec 2014 12:48:45 +0000 Subject: Added an example of custom Indexers in C-Sharp [en] --- csharp.html.markdown | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index f6708590..47dd9683 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -678,6 +678,23 @@ on a new line! ""Wow!"", the masses cried"; private set; } + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" } + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + //Method to display the attribute values of this Object. public virtual string Info() { -- cgit v1.2.3 From 928b8404aa7d47dbc50351f48fdca7334bb32647 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 20:10:40 +0100 Subject: [CSharp/en]XML Comments can be used for external doc generation and for help within the IDE --- csharp.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 47dd9683..ad43e607 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -18,8 +18,10 @@ C# is an elegant and type-safe object-oriented language that enables developers Multi-line comments look like this */ /// -/// 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 /// +//public void MethodOrClassOrOtherWithParsableHelp() {} // Specify namespaces application will be using using System; -- cgit v1.2.3 From 937e6dad51446cf47c85156e4af0696efdcac43b Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 20:21:52 +0100 Subject: [CSharp/en]namespaces can have multiple levels with dots --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index ad43e607..4a238f25 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -35,7 +35,7 @@ using System.Threading.Tasks; using System.IO; // defines scope to organize code into "packages" -namespace Learning +namespace LearningXInYMinutes.CSharp { // 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. -- cgit v1.2.3 From 012a4a8e901eda4fa89e151f398c67500af8acb9 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 20:42:27 +0100 Subject: [CSharp/en]Fixed compilation and ef errors --- csharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 4a238f25..d3738b39 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -26,7 +26,7 @@ Multi-line comments look like this // Specify namespaces application will be using using System; using System.Collections.Generic; -using System.Data.Entity; +using System.Data.Entity; // Add dll reference with NuGet: Install-Package EntityFramework using System.Dynamic; using System.Linq; using System.Linq.Expressions; @@ -684,7 +684,7 @@ on a new line! ""Wow!"", the masses cried"; // All though this is not entirely useful in this example, you // could do bicycle[0] which yields "chris" to get the first passenger or // 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] { @@ -786,7 +786,7 @@ on a new line! ""Wow!"", the masses cried"; /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// - public class BikeRepository : DbSet + public class BikeRepository : DbContext { public BikeRepository() : base() -- cgit v1.2.3 From 1d4bb253fd8b6053e5a38d206ffc15360d3bd6fd Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 20:56:56 +0100 Subject: [CSharp/en]Constants are TitleCase, not SCREAMING_CAPS in C# (as done everywhere in the .NET framework, encouraged by the MS .NET framework guidelines and StackOverflow: http://stackoverflow.com/a/242549/540352) --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index d3738b39..88c2db35 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -127,7 +127,7 @@ on a new line! ""Wow!"", the masses cried"; // Use const or read-only to make a variable immutable // const values are calculated at compile time - const int HOURS_I_WORK_PER_WEEK = 9001; + const int HoursWorkPerWeek = 9001; /////////////////////////////////////////////////// // Data Structures -- cgit v1.2.3 From 495e38612160ac373325543de3c5b88e0ef6ed35 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 21:40:21 +0100 Subject: [CSharp/en]break and continue in loops --- csharp.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 88c2db35..9f66b8ff 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -244,8 +244,15 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //Iterated 100 times, fooDoWhile 0->99 + // Start iteration 100 times, fooDoWhile 0->99 + if (false) + continue; // skip the current iteration + fooDoWhile++; + + if (fooDoWhile == 50) + break; // breaks from the loop completely + } while (fooDoWhile < 100); //for loop structure => for(; ; ) @@ -303,7 +310,7 @@ on a new line! ""Wow!"", the masses cried"; // Converting data // Convert String To Integer - // this will throw an Exception on failure + // this will throw a Exception on failure int.Parse("123");//returns an integer version of "123" // try parse will default to type default on failure -- cgit v1.2.3 From 69e38974aec4d149944e551867c1412dfcf2bed7 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 21:41:46 +0100 Subject: [CSharp/en]added casting to converting --- csharp.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 9f66b8ff..fceda4ff 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -310,7 +310,7 @@ on a new line! ""Wow!"", the masses cried"; // Converting data // Convert String To Integer - // this will throw a Exception on failure + // this will throw a FormatException on failure int.Parse("123");//returns an integer version of "123" // try parse will default to type default on failure @@ -324,6 +324,11 @@ on a new line! ""Wow!"", the masses cried"; Convert.ToString(123); // or tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; } /////////////////////////////////////// -- cgit v1.2.3 From 04c4433433f313884fe38f126b24ff52b59f3af1 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 21:45:13 +0100 Subject: [CSharp/en]Added ref and out parameters --- csharp.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index fceda4ff..8eda5356 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -380,6 +380,15 @@ on a new line! ""Wow!"", the masses cried"; return -1; } + // Methods can have the same name, as long as the signature is unique + // 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 + } + // Methods can have the same name, as long as the signature is unique public static void MethodSignatures(string maxCount) { @@ -414,6 +423,10 @@ on a new line! ""Wow!"", the masses cried"; MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); 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 int i = 3; i.Print(); // Defined below -- cgit v1.2.3 From 4f8b16f81745c4082945b49e631aadd204564626 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 22:05:11 +0100 Subject: [CSharp/en]Added static property --- csharp.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 8eda5356..61db6a8a 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -625,7 +625,7 @@ on a new line! ""Wow!"", the masses cried"; // Static members belong to the type itself rather then specific object. // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); - static public int BicyclesCreated = 0; + public static int BicyclesCreated { get; set; } // readonly values are set at run time // they can only be assigned upon declaration or in a constructor @@ -827,7 +827,6 @@ on a new line! ""Wow!"", the masses cried"; * Flags * Attributes - * Static properties * Exceptions, Abstraction * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms -- cgit v1.2.3 From dc34af2b5de78fb7e7f04e982e145d0bd67a3728 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 22:34:42 +0100 Subject: [CSharp/en]Added [Flags] --- csharp.html.markdown | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 61db6a8a..4258a0c6 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -622,6 +622,22 @@ on a new line! ""Wow!"", the masses cried"; 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, + Full = 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. // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); @@ -825,7 +841,6 @@ on a new line! ""Wow!"", the masses cried"; ## Topics Not Covered - * Flags * Attributes * Exceptions, Abstraction * ASP.NET (Web Forms/MVC/WebMatrix) -- cgit v1.2.3 From 710f9fa03b5cea3d60906edb977133e37a19ebf6 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 23:14:58 +0100 Subject: [CSharp/en]Added exception handling --- csharp.html.markdown | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 4258a0c6..df265d8c 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -462,6 +462,31 @@ on a new line! ""Wow!"", the masses cried"; Func square = (x) => x * x; // Last T item is the return value 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. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of @@ -780,10 +805,17 @@ on a new line! ""Wow!"", the masses cried"; } 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() { string result = "PennyFarthing bicycle "; @@ -842,7 +874,7 @@ on a new line! ""Wow!"", the masses cried"; ## Topics Not Covered * Attributes - * Exceptions, Abstraction + * Abstraction * ASP.NET (Web Forms/MVC/WebMatrix) * Winforms * Windows Presentation Foundation (WPF) -- cgit v1.2.3 From 90e8dac0b8f5ad4cb0e9218cc05457da48dd4e98 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 31 Jan 2015 23:39:41 +0100 Subject: [CSharp/en]updated topics not covered + added myself :) --- csharp.html.markdown | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index df265d8c..fc7588f8 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] filename: LearnCSharp.cs --- @@ -874,10 +875,14 @@ on a new line! ""Wow!"", the masses cried"; ## Topics Not Covered * Attributes - * Abstraction - * ASP.NET (Web Forms/MVC/WebMatrix) - * Winforms - * Windows Presentation Foundation (WPF) + * async/await, yield, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) ## Further Reading @@ -890,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 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) - - - -[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) -- cgit v1.2.3 From f5d0208178d9903911249dad482cec37f5523627 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sun, 1 Feb 2015 00:04:10 +0100 Subject: [CSharp/en]Fixes for my own changes --- csharp.html.markdown | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index fc7588f8..58d5fa11 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -326,7 +326,7 @@ on a new line! ""Wow!"", the masses cried"; // or tryInt.ToString(); - // Casting + // Casting // Cast decimal 15 to a int // and then implicitly cast to long long x = (int) 15M; @@ -390,11 +390,6 @@ on a new line! ""Wow!"", the masses cried"; count = 15; // out param must be assigned before control leaves the method } - // Methods can have the same name, as long as the signature is unique - public static void MethodSignatures(string maxCount) - { - } - // GENERICS // The classes for TKey and TValue is specified by the user calling this function. // This method emulates the SetDefault of Python @@ -657,7 +652,7 @@ on a new line! ""Wow!"", the masses cried"; MudGuards = 2, // need to set the values manually! Racks = 4, Lights = 8, - Full = Bell | MudGuards | Racks | Lights + FullPackage = Bell | MudGuards | Racks | Lights } // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) -- cgit v1.2.3 From 8911f368de43ab33d0d5ac251551de1ee765727c Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sun, 1 Feb 2015 06:01:01 +0100 Subject: [CSharp/en]extra details for using EntityFramework and namespaces --- csharp.html.markdown | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 58d5fa11..87a70200 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -24,19 +24,24 @@ Multi-line comments look like this /// //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.Collections.Generic; -using System.Data.Entity; // Add dll reference with NuGet: Install-Package EntityFramework using System.Dynamic; using System.Linq; -using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; using System.IO; -// defines scope to organize code into "packages" -namespace LearningXInYMinutes.CSharp +// But this is one is not: +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 // you're allowed to do otherwise, but shouldn't for sanity. -- cgit v1.2.3 From 031637455c6fef9ea51dbe1073129c4871ad10d9 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sun, 1 Feb 2015 19:01:47 +0100 Subject: [CSharp/en]Fixed typo --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 87a70200..479b7f01 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -34,7 +34,7 @@ using System.Net; using System.Threading.Tasks; using System.IO; -// But this is one is not: +// But this one is not: 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` -- cgit v1.2.3 From f1a90a4e636616ce91a271504eee3f374bfd7094 Mon Sep 17 00:00:00 2001 From: Guntbert Reiter Date: Sun, 4 Oct 2015 16:44:24 +0200 Subject: Put demonstrative condition into ternary expression It should be made clear that the part before the ternary operator is indeed a condition, most often created as some comparison expression. --- csharp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 479b7f01..222ba0d2 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -236,7 +236,8 @@ on a new line! ""Wow!"", the masses cried"; // Ternary operators // A simple if/else can be written as follows // ? : - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While loop int fooWhile = 0; -- cgit v1.2.3 From 960ee4a1856db8eadb96277bb2422edfa8f2a81c Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 23:11:24 -0400 Subject: removing whitespace all over --- csharp.html.markdown | 56 ++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) (limited to 'csharp.html.markdown') diff --git a/csharp.html.markdown b/csharp.html.markdown index 222ba0d2..02650038 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -25,7 +25,7 @@ Multi-line comments look like this //public void MethodOrClassOrOtherWithParsableHelp() {} // Specify the namespaces this source code will be using -// The namespaces below are all part of the standard .NET Framework Class Libary +// The namespaces below are all part of the standard .NET Framework Class Libary using System; using System.Collections.Generic; using System.Dynamic; @@ -48,7 +48,7 @@ namespace Learning.CSharp public class LearnCSharp { // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before - public static void Syntax() + public static void Syntax() { // Use Console.WriteLine to print lines Console.WriteLine("Hello World"); @@ -371,11 +371,11 @@ on a new line! ""Wow!"", the masses cried"; // // INTERESTING FEATURES // - + // DEFAULT METHOD SIGNATURES public // Visibility - static // Allows for direct call on class without object + static // Allows for direct call on class without object int // Return Type, MethodSignatures( int maxCount, // First variable, expects an int @@ -383,7 +383,7 @@ on a new line! ""Wow!"", the masses cried"; int another = 3, params string[] otherParams // captures all other parameters passed to method ) - { + { return -1; } @@ -400,8 +400,8 @@ on a new line! ""Wow!"", the masses cried"; // The classes for TKey and TValue is specified by the user calling this function. // This method emulates the SetDefault of Python public static TValue SetDefault( - IDictionary dictionary, - TKey key, + IDictionary dictionary, + TKey key, TValue defaultItem) { TValue result; @@ -410,7 +410,7 @@ on a new line! ""Wow!"", the masses cried"; return result; } - // You can narrow down the objects that are passed in + // You can narrow down the objects that are passed in public static void IterateAndPrint(T toPrint) where T: IEnumerable { // We can iterate, since T is a IEnumerable @@ -450,13 +450,13 @@ on a new line! ""Wow!"", the masses cried"; // GENERICS // - var phonebook = new Dictionary() { + var phonebook = new Dictionary() { {"Sarah", "212 555 5555"} // Add some entries to the phone book }; // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone - // nb, you don't need to specify the TKey and TValue since they can be + // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 @@ -491,26 +491,26 @@ on a new line! ""Wow!"", the masses cried"; // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. // 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 // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); // At the end of scope, resources will be released. // Even if an exception is thrown. - } + } // PARALLEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", "http://www.shaunmccarthy.com" }; var responses = new Dictionary(); - + // Will spin up separate threads for each request, and join on them // before going to the next step! - Parallel.ForEach(websites, + Parallel.ForEach(websites, new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads website => { @@ -534,7 +534,7 @@ on a new line! ""Wow!"", the masses cried"; (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); - // IQUERYABLE - almost all collections implement this, which gives you a lot of + // IQUERYABLE - almost all collections implement this, which gives you a lot of // very useful Map / Filter / Reduce style methods var bikes = new List(); bikes.Sort(); // Sorts the array @@ -556,8 +556,8 @@ on a new line! ""Wow!"", the masses cried"; // ASPARALLEL // And this is where things get wicked - combines linq and parallel operations var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // this will happen in parallel! Threads will automagically be spun up and the - // results divvied amongst them! Amazing for large datasets when you have lots of + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of // cores // LINQ - maps a store to IQueryable objects, with delayed execution @@ -575,9 +575,9 @@ on a new line! ""Wow!"", the masses cried"; .Select(b => b.Name); // still no query run // Now the query runs, but opens a reader, so only populates are you iterate through - foreach (string bike in query) + foreach (string bike in query) Console.WriteLine(result); - + } @@ -629,7 +629,7 @@ on a new line! ""Wow!"", the masses cried"; private set; // You can set modifiers on the get/set methods } - int _speed; // Everything is private by default: Only accessible from within this class. + int _speed; // Everything is private by default: Only accessible from within this class. // can also use keyword private public string Name { get; set; } @@ -676,7 +676,7 @@ on a new line! ""Wow!"", the masses cried"; // Constructors are a way of creating classes // This is a default constructor - public Bicycle() + public Bicycle() { this.Gear = 1; // you can access members of the object with the keyword this Cadence = 50; // but you don't always need it @@ -688,13 +688,13 @@ on a new line! ""Wow!"", the masses cried"; // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, BikeBrand brand) + string name, bool hasCardsInSpokes, BikeBrand brand) : base() // calls base first { - Gear = startGear; + Gear = startGear; Cadence = startCadence; _speed = startSpeed; - Name = name; + Name = name; _hasCardsInSpokes = hasCardsInSpokes; Brand = brand; } @@ -857,7 +857,7 @@ on a new line! ""Wow!"", the masses cried"; } /// - /// Used to connect to DB for LinqToSql example. + /// Used to connect to DB for LinqToSql example. /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// @@ -882,7 +882,7 @@ on a new line! ""Wow!"", the masses cried"; * ASP.NET Web Forms (old) * WebMatrix (tool) * Desktop Development - * Windows Presentation Foundation (WPF) (new) + * Windows Presentation Foundation (WPF) (new) * Winforms (old) ## Further Reading -- cgit v1.2.3