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