mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-01-13 12:45:58 +00:00
Line length edits to C#
This commit is contained in:
parent
dbf07b80ac
commit
93fc8f5e80
@ -28,492 +28,493 @@ using System.Collections.Generic;
|
|||||||
// defines scope to organize code into "packages"
|
// defines scope to organize code into "packages"
|
||||||
namespace Learning
|
namespace Learning
|
||||||
{
|
{
|
||||||
// Each .cs file should at least contain a class with the same name as the file
|
// Each .cs file should at least contain a class with the same name as the file
|
||||||
// you're allowed to do otherwise, but shouldn't for sanity.
|
// you're allowed to do otherwise, but shouldn't for sanity.
|
||||||
public class LearnCSharp
|
public class LearnCSharp
|
||||||
{
|
{
|
||||||
// A console application must have a main method as an entry point
|
// A console application must have a main method as an entry point
|
||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
// Use Console.WriteLine to print lines
|
// Use Console.WriteLine to print lines
|
||||||
Console.WriteLine("Hello World");
|
Console.WriteLine("Hello World");
|
||||||
Console.WriteLine(
|
Console.WriteLine(
|
||||||
"Integer: " + 10 +
|
"Integer: " + 10 +
|
||||||
" Double: " + 3.14 +
|
" Double: " + 3.14 +
|
||||||
" Boolean: " + true);
|
" Boolean: " + true);
|
||||||
|
|
||||||
// To print without a new line, use Console.Write
|
// To print without a new line, use Console.Write
|
||||||
Console.Write("Hello ");
|
Console.Write("Hello ");
|
||||||
Console.Write("World");
|
Console.Write("World");
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////////////////
|
///////////////////////////////////////////////////
|
||||||
// Types & Variables
|
// Types & Variables
|
||||||
//
|
//
|
||||||
// Declare a variable using <type> <name>
|
// Declare a variable using <type> <name>
|
||||||
///////////////////////////////////////////////////
|
///////////////////////////////////////////////////
|
||||||
|
|
||||||
// Sbyte - Signed 8-bit integer
|
// Sbyte - Signed 8-bit integer
|
||||||
// (-128 <= sbyte <= 127)
|
// (-128 <= sbyte <= 127)
|
||||||
sbyte fooSbyte = 100;
|
sbyte fooSbyte = 100;
|
||||||
|
|
||||||
// Byte - Unsigned 8-bit integer
|
// Byte - Unsigned 8-bit integer
|
||||||
// (0 <= byte <= 255)
|
// (0 <= byte <= 255)
|
||||||
byte fooByte = 100;
|
byte fooByte = 100;
|
||||||
|
|
||||||
// Short - Signed 16-bit integer
|
// Short - Signed 16-bit integer
|
||||||
// (-32,768 <= short <= 32,767)
|
// (-32,768 <= short <= 32,767)
|
||||||
short fooShort = 10000;
|
short fooShort = 10000;
|
||||||
|
|
||||||
// Ushort - Unsigned 16-bit integer
|
// Ushort - Unsigned 16-bit integer
|
||||||
// (0 <= ushort <= 65,535)
|
// (0 <= ushort <= 65,535)
|
||||||
ushort fooUshort = 10000;
|
ushort fooUshort = 10000;
|
||||||
|
|
||||||
// Integer - Signed 32-bit integer
|
// Integer - Signed 32-bit integer
|
||||||
// (-2,147,483,648 <= int <= 2,147,483,647)
|
// (-2,147,483,648 <= int <= 2,147,483,647)
|
||||||
int fooInt = 1;
|
int fooInt = 1;
|
||||||
|
|
||||||
// Uinteger - Unsigned 32-bit integer
|
// Uinteger - Unsigned 32-bit integer
|
||||||
// (0 <= uint <= 4,294,967,295)
|
// (0 <= uint <= 4,294,967,295)
|
||||||
uint fooUint = 1;
|
uint fooUint = 1;
|
||||||
|
|
||||||
// Long - Signed 64-bit integer
|
// Long - Signed 64-bit integer
|
||||||
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
|
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
|
||||||
long fooLong = 100000L;
|
long fooLong = 100000L;
|
||||||
// L is used to denote that this variable value is of type long or ulong
|
// 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.
|
// anything without is treated as int or uint depending on size.
|
||||||
|
|
||||||
// Ulong - Unsigned 64-bit integer
|
// Ulong - Unsigned 64-bit integer
|
||||||
// (0 <= ulong <= 18,446,744,073,709,551,615)
|
// (0 <= ulong <= 18,446,744,073,709,551,615)
|
||||||
ulong fooUlong = 100000L;
|
ulong fooUlong = 100000L;
|
||||||
|
|
||||||
// Float - Single-precision 32-bit IEEE 754 Floating Point
|
// Float - Single-precision 32-bit IEEE 754 Floating Point
|
||||||
// Precision: 7 digits
|
// Precision: 7 digits
|
||||||
float fooFloat = 234.5f;
|
float fooFloat = 234.5f;
|
||||||
// f is used to denote that this variable value is of type float;
|
// f is used to denote that this variable value is of type float;
|
||||||
// otherwise it is treated as double.
|
// otherwise it is treated as double.
|
||||||
|
|
||||||
// Double - Double-precision 64-bit IEEE 754 Floating Point
|
// Double - Double-precision 64-bit IEEE 754 Floating Point
|
||||||
// Precision: 15-16 digits
|
// Precision: 15-16 digits
|
||||||
double fooDouble = 123.4;
|
double fooDouble = 123.4;
|
||||||
|
|
||||||
// Bool - true & false
|
// Bool - true & false
|
||||||
bool fooBoolean = true;
|
bool fooBoolean = true;
|
||||||
bool barBoolean = false;
|
bool barBoolean = false;
|
||||||
|
|
||||||
// Char - A single 16-bit Unicode character
|
// Char - A single 16-bit Unicode character
|
||||||
char fooChar = 'A';
|
char fooChar = 'A';
|
||||||
|
|
||||||
// Strings
|
// Strings
|
||||||
string fooString = "My string is here!";
|
string fooString = "My string is here!";
|
||||||
Console.WriteLine(fooString);
|
Console.WriteLine(fooString);
|
||||||
|
|
||||||
// formatting
|
// formatting
|
||||||
string fooFormattedString = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
|
string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
|
||||||
Console.WriteLine(fooFormattedString);
|
Console.WriteLine(fooFormattedString);
|
||||||
|
|
||||||
// formatting dates
|
// formatting dates
|
||||||
DateTime fooDate = DateTime.Now;
|
DateTime fooDate = DateTime.Now;
|
||||||
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
|
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
|
||||||
|
|
||||||
// \n is an escaped character that starts a new line
|
// \n is an escaped character that starts a new line
|
||||||
string barString = "Printing on a new line?\nNo Problem!";
|
string barString = "Printing on a new line?\nNo Problem!";
|
||||||
Console.WriteLine(barString);
|
Console.WriteLine(barString);
|
||||||
|
|
||||||
// it can be written prettier by using the @ symbol
|
// it can be written prettier by using the @ symbol
|
||||||
string bazString = @"Here's some stuff
|
string bazString = @"Here's some stuff
|
||||||
on a new line!";
|
on a new line!";
|
||||||
Console.WriteLine(bazString);
|
Console.WriteLine(bazString);
|
||||||
|
|
||||||
// quotes need to be escaped
|
// quotes need to be escaped
|
||||||
// use \" normally
|
// use \" normally
|
||||||
string quotedString = "some \"quoted\" stuff";
|
string quotedString = "some \"quoted\" stuff";
|
||||||
Console.WriteLine(quotedString);
|
Console.WriteLine(quotedString);
|
||||||
|
|
||||||
// use "" when strings start with @
|
// use "" when strings start with @
|
||||||
string quotedString2 = @"some MORE ""quoted"" stuff";
|
string quotedString2 = @"some MORE ""quoted"" stuff";
|
||||||
Console.WriteLine(quotedString2);
|
Console.WriteLine(quotedString2);
|
||||||
|
|
||||||
// Use const or read-only to make a variable immutable
|
// Use const or read-only to make a variable immutable
|
||||||
// const values are calculated at compile time
|
// const values are calculated at compile time
|
||||||
const int HOURS_I_WORK_PER_WEEK = 9001;
|
const int HOURS_I_WORK_PER_WEEK = 9001;
|
||||||
|
|
||||||
// Nullable types
|
// Nullable types
|
||||||
// any type can be made nullable by suffixing a ?
|
// any type can be made nullable by suffixing a ?
|
||||||
// <type>? <var name> = <value>
|
// <type>? <var name> = <value>
|
||||||
int? nullable = null;
|
int? nullable = null;
|
||||||
Console.WriteLine("Nullable variable: " + nullable);
|
Console.WriteLine("Nullable variable: " + nullable);
|
||||||
|
|
||||||
// ?? is syntactic sugar for specifying default value
|
// ?? is syntactic sugar for specifying default value
|
||||||
// in case variable is null
|
// in case variable is null
|
||||||
int notNullable = nullable ?? 0;
|
int notNullable = nullable ?? 0;
|
||||||
Console.WriteLine("Not nullable variable: " + notNullable);
|
Console.WriteLine("Not nullable variable: " + notNullable);
|
||||||
|
|
||||||
// Var - compiler will choose the most appropriate type based on value
|
// Var - compiler will choose the most appropriate type based on value
|
||||||
var fooImplicit = true;
|
var fooImplicit = true;
|
||||||
|
|
||||||
///////////////////////////////////////////////////
|
///////////////////////////////////////////////////
|
||||||
// Data Structures
|
// Data Structures
|
||||||
///////////////////////////////////////////////////
|
///////////////////////////////////////////////////
|
||||||
Console.WriteLine("\n->Data Structures");
|
Console.WriteLine("\n->Data Structures");
|
||||||
|
|
||||||
// Arrays
|
// Arrays
|
||||||
// The array size must be decided upon declaration
|
// The array size must be decided upon declaration
|
||||||
// The format for declaring an array is follows:
|
// The format for declaring an array is follows:
|
||||||
// <datatype>[] <var name> = new <datatype>[<array size>];
|
// <datatype>[] <var name> = new <datatype>[<array size>];
|
||||||
int[] intArray = new int[10];
|
int[] intArray = new int[10];
|
||||||
string[] stringArray = new string[1];
|
string[] stringArray = new string[1];
|
||||||
bool[] boolArray = new bool[100];
|
bool[] boolArray = new bool[100];
|
||||||
|
|
||||||
// Another way to declare & initialize an array
|
// Another way to declare & initialize an array
|
||||||
int[] y = { 9000, 1000, 1337 };
|
int[] y = { 9000, 1000, 1337 };
|
||||||
|
|
||||||
// Indexing an array - Accessing an element
|
// Indexing an array - Accessing an element
|
||||||
Console.WriteLine("intArray @ 0: " + intArray[0]);
|
Console.WriteLine("intArray @ 0: " + intArray[0]);
|
||||||
|
|
||||||
// Arrays are zero-indexed and mutable.
|
// Arrays are zero-indexed and mutable.
|
||||||
intArray[1] = 1;
|
intArray[1] = 1;
|
||||||
Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1
|
Console.WriteLine("intArray @ 1: " + intArray[1]); // => 1
|
||||||
|
|
||||||
// Lists
|
// Lists
|
||||||
// Lists are used more frequently than arrays as they are more flexible
|
// Lists are used more frequently than arrays as they are more flexible
|
||||||
// The format for declaring a list is follows:
|
// The format for declaring a list is follows:
|
||||||
// List<datatype> <var name> = new List<datatype>();
|
// List<datatype> <var name> = new List<datatype>();
|
||||||
List<int> intList = new List<int>();
|
List<int> intList = new List<int>();
|
||||||
List<string> stringList = new List<string>();
|
List<string> stringList = new List<string>();
|
||||||
|
|
||||||
// Another way to declare & initialize a list
|
// Another way to declare & initialize a list
|
||||||
List<int> z = new List<int> { 9000, 1000, 1337 };
|
List<int> z = new List<int> { 9000, 1000, 1337 };
|
||||||
|
|
||||||
// Indexing a list - Accessing an element
|
// Indexing a list - Accessing an element
|
||||||
// Lists are zero-indexed and mutable.
|
// Lists are zero-indexed and mutable.
|
||||||
Console.WriteLine("z @ 0: " + z[2]);
|
Console.WriteLine("z @ 0: " + z[2]);
|
||||||
|
|
||||||
// Lists don't default to a value;
|
// Lists don't default to a value;
|
||||||
// A value must be added before accessing the index
|
// A value must be added before accessing the index
|
||||||
intList.Add(1);
|
intList.Add(1);
|
||||||
Console.WriteLine("intList @ 0: " + intList[0]);
|
Console.WriteLine("intList @ 0: " + intList[0]);
|
||||||
|
|
||||||
|
|
||||||
// Others data structures to check out:
|
// Others data structures to check out:
|
||||||
//
|
//
|
||||||
// Stack/Queue
|
// Stack/Queue
|
||||||
// Dictionary
|
// Dictionary
|
||||||
// Read-only Collections
|
// Read-only Collections
|
||||||
// Tuple (.Net 4+)
|
// Tuple (.Net 4+)
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Operators
|
// Operators
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
Console.WriteLine("\n->Operators");
|
Console.WriteLine("\n->Operators");
|
||||||
|
|
||||||
int i1 = 1, i2 = 2; // Shorthand for multiple declarations
|
int i1 = 1, i2 = 2; // Shorthand for multiple declarations
|
||||||
|
|
||||||
// Arithmetic is straightforward
|
// Arithmetic is straightforward
|
||||||
Console.WriteLine("1+2 = " + (i1 + i2)); // => 3
|
Console.WriteLine("1+2 = " + (i1 + i2)); // => 3
|
||||||
Console.WriteLine("2-1 = " + (i2 - i1)); // => 1
|
Console.WriteLine("2-1 = " + (i2 - i1)); // => 1
|
||||||
Console.WriteLine("2*1 = " + (i2 * i1)); // => 2
|
Console.WriteLine("2*1 = " + (i2 * i1)); // => 2
|
||||||
Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
|
Console.WriteLine("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
|
||||||
|
|
||||||
// Modulo
|
// Modulo
|
||||||
Console.WriteLine("11%3 = " + (11 % 3)); // => 2
|
Console.WriteLine("11%3 = " + (11 % 3)); // => 2
|
||||||
|
|
||||||
// Comparison operators
|
// Comparison operators
|
||||||
Console.WriteLine("3 == 2? " + (3 == 2)); // => false
|
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)); // => true
|
Console.WriteLine("3 > 2? " + (3 > 2)); // => true
|
||||||
Console.WriteLine("3 < 2? " + (3 < 2)); // => false
|
Console.WriteLine("3 < 2? " + (3 < 2)); // => false
|
||||||
Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
|
Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
|
||||||
Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
|
Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
|
||||||
|
|
||||||
// Bitwise operators!
|
// Bitwise operators!
|
||||||
/*
|
/*
|
||||||
~ Unary bitwise complement
|
~ Unary bitwise complement
|
||||||
<< Signed left shift
|
<< Signed left shift
|
||||||
>> Signed right shift
|
>> Signed right shift
|
||||||
>>> Unsigned right shift
|
>>> Unsigned right shift
|
||||||
& Bitwise AND
|
& Bitwise AND
|
||||||
^ Bitwise exclusive OR
|
^ Bitwise exclusive OR
|
||||||
| Bitwise inclusive OR
|
| Bitwise inclusive OR
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Incrementations
|
// Incrementations
|
||||||
int i = 0;
|
int i = 0;
|
||||||
Console.WriteLine("\n->Inc/Dec-rementation");
|
Console.WriteLine("\n->Inc/Dec-rementation");
|
||||||
Console.WriteLine(i++); //i = 1. Post-Incrementation
|
Console.WriteLine(i++); //i = 1. Post-Incrementation
|
||||||
Console.WriteLine(++i); //i = 2. Pre-Incrementation
|
Console.WriteLine(++i); //i = 2. Pre-Incrementation
|
||||||
Console.WriteLine(i--); //i = 1. Post-Decrementation
|
Console.WriteLine(i--); //i = 1. Post-Decrementation
|
||||||
Console.WriteLine(--i); //i = 0. Pre-Decrementation
|
Console.WriteLine(--i); //i = 0. Pre-Decrementation
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Control Structures
|
// Control Structures
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
Console.WriteLine("\n->Control Structures");
|
Console.WriteLine("\n->Control Structures");
|
||||||
|
|
||||||
// If statements are c-like
|
// If statements are c-like
|
||||||
int j = 10;
|
int j = 10;
|
||||||
if (j == 10)
|
if (j == 10)
|
||||||
{
|
{
|
||||||
Console.WriteLine("I get printed");
|
Console.WriteLine("I get printed");
|
||||||
}
|
}
|
||||||
else if (j > 10)
|
else if (j > 10)
|
||||||
{
|
{
|
||||||
Console.WriteLine("I don't");
|
Console.WriteLine("I don't");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Console.WriteLine("I also don't");
|
Console.WriteLine("I also don't");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ternary operators
|
// Ternary operators
|
||||||
// A simple if/else can be written as follows
|
// A simple if/else can be written as follows
|
||||||
// <condition> ? <true> : <false>
|
// <condition> ? <true> : <false>
|
||||||
string isTrue = (true) ? "True" : "False";
|
string isTrue = (true) ? "True" : "False";
|
||||||
Console.WriteLine("Ternary demo: " + isTrue);
|
Console.WriteLine("Ternary demo: " + isTrue);
|
||||||
|
|
||||||
|
|
||||||
// While loop
|
// While loop
|
||||||
int fooWhile = 0;
|
int fooWhile = 0;
|
||||||
while (fooWhile < 100)
|
while (fooWhile < 100)
|
||||||
{
|
{
|
||||||
//Console.WriteLine(fooWhile);
|
//Console.WriteLine(fooWhile);
|
||||||
//Increment the counter
|
//Increment the counter
|
||||||
//Iterated 99 times, fooWhile 0->99
|
//Iterated 99 times, fooWhile 0->99
|
||||||
fooWhile++;
|
fooWhile++;
|
||||||
}
|
}
|
||||||
Console.WriteLine("fooWhile Value: " + fooWhile);
|
Console.WriteLine("fooWhile Value: " + fooWhile);
|
||||||
|
|
||||||
// Do While Loop
|
// Do While Loop
|
||||||
int fooDoWhile = 0;
|
int fooDoWhile = 0;
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
//Console.WriteLine(fooDoWhile);
|
//Console.WriteLine(fooDoWhile);
|
||||||
//Increment the counter
|
//Increment the counter
|
||||||
//Iterated 99 times, fooDoWhile 0->99
|
//Iterated 99 times, fooDoWhile 0->99
|
||||||
fooDoWhile++;
|
fooDoWhile++;
|
||||||
} while (fooDoWhile < 100);
|
} while (fooDoWhile < 100);
|
||||||
Console.WriteLine("fooDoWhile Value: " + fooDoWhile);
|
Console.WriteLine("fooDoWhile Value: " + fooDoWhile);
|
||||||
|
|
||||||
// For Loop
|
// For Loop
|
||||||
int fooFor;
|
int fooFor;
|
||||||
//for loop structure => for(<start_statement>; <conditional>; <step>)
|
//for loop structure => for(<start_statement>; <conditional>; <step>)
|
||||||
for (fooFor = 0; fooFor < 10; fooFor++)
|
for (fooFor = 0; fooFor < 10; fooFor++)
|
||||||
{
|
{
|
||||||
//Console.WriteLine(fooFor);
|
//Console.WriteLine(fooFor);
|
||||||
//Iterated 10 times, fooFor 0->9
|
//Iterated 10 times, fooFor 0->9
|
||||||
}
|
}
|
||||||
Console.WriteLine("fooFor Value: " + fooFor);
|
Console.WriteLine("fooFor Value: " + fooFor);
|
||||||
|
|
||||||
// Switch Case
|
// Switch Case
|
||||||
// A switch works with the byte, short, char, and int data types.
|
// A switch works with the byte, short, char, and int data types.
|
||||||
// It also works with enumerated types (discussed in Enum Types),
|
// It also works with enumerated types (discussed in Enum Types),
|
||||||
// the String class, and a few special classes that wrap
|
// the String class, and a few special classes that wrap
|
||||||
// primitive types: Character, Byte, Short, and Integer.
|
// primitive types: Character, Byte, Short, and Integer.
|
||||||
int month = 3;
|
int month = 3;
|
||||||
string monthString;
|
string monthString;
|
||||||
switch (month)
|
switch (month)
|
||||||
{
|
{
|
||||||
case 1:
|
case 1:
|
||||||
monthString = "January";
|
monthString = "January";
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
monthString = "February";
|
monthString = "February";
|
||||||
break;
|
break;
|
||||||
case 3:
|
case 3:
|
||||||
monthString = "March";
|
monthString = "March";
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
monthString = "Some other month";
|
monthString = "Some other month";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Console.WriteLine("Switch Case Result: " + monthString);
|
Console.WriteLine("Switch Case Result: " + monthString);
|
||||||
|
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Converting Data Types And Typcasting
|
// Converting Data Types And Typcasting
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
// Converting data
|
// Converting data
|
||||||
|
|
||||||
// Convert String To Integer
|
// Convert String To Integer
|
||||||
// this will throw an Exception on failure
|
// this will throw an Exception on failure
|
||||||
int.Parse("123");//returns an integer version of "123"
|
int.Parse("123");//returns an integer version of "123"
|
||||||
|
|
||||||
// try parse will default to type default on failure
|
// try parse will default to type default on failure
|
||||||
// in this case: 0
|
// in this case: 0
|
||||||
int tryInt;
|
int tryInt;
|
||||||
int.TryParse("123", out tryInt);
|
int.TryParse("123", out tryInt);
|
||||||
|
|
||||||
// Convert Integer To String
|
// Convert Integer To String
|
||||||
// Convert class has a number of methods to facilitate conversions
|
// Convert class has a number of methods to facilitate conversions
|
||||||
Convert.ToString(123);
|
Convert.ToString(123);
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Classes And Functions
|
// Classes And Functions
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
|
|
||||||
Console.WriteLine("\n->Classes & Functions");
|
Console.WriteLine("\n->Classes & Functions");
|
||||||
|
|
||||||
// (definition of the Bicycle class follows)
|
// (definition of the Bicycle class follows)
|
||||||
|
|
||||||
// Use new to instantiate a class
|
// Use new to instantiate a class
|
||||||
Bicycle trek = new Bicycle();
|
Bicycle trek = new Bicycle();
|
||||||
|
|
||||||
// Call object methods
|
// Call object methods
|
||||||
trek.speedUp(3); // You should always use setter and getter methods
|
trek.speedUp(3); // You should always use setter and getter methods
|
||||||
trek.setCadence(100);
|
trek.setCadence(100);
|
||||||
|
|
||||||
// ToString is a convention to display the value of this Object.
|
// ToString is a convention to display the value of this Object.
|
||||||
Console.WriteLine("trek info: " + trek.ToString());
|
Console.WriteLine("trek info: " + trek.ToString());
|
||||||
|
|
||||||
// Instantiate another new Bicycle
|
// Instantiate another new Bicycle
|
||||||
Bicycle octo = new Bicycle(5, 10);
|
Bicycle octo = new Bicycle(5, 10);
|
||||||
Console.WriteLine("octo info: " + octo.ToString());
|
Console.WriteLine("octo info: " + octo.ToString());
|
||||||
|
|
||||||
// Instantiate a new Penny Farthing
|
// Instantiate a new Penny Farthing
|
||||||
PennyFarthing funbike = new PennyFarthing(1, 10);
|
PennyFarthing funbike = new PennyFarthing(1, 10);
|
||||||
Console.WriteLine("funbike info: " + funbike.ToString());
|
Console.WriteLine("funbike info: " + funbike.ToString());
|
||||||
|
|
||||||
Console.Read();
|
Console.Read();
|
||||||
} // End main method
|
} // End main method
|
||||||
|
|
||||||
|
|
||||||
} // End LearnCSharp class
|
} // End LearnCSharp class
|
||||||
|
|
||||||
// You can include other classes in a .cs file
|
// You can include other classes in a .cs file
|
||||||
|
|
||||||
|
|
||||||
// Class Declaration Syntax:
|
// Class Declaration Syntax:
|
||||||
// <public/private/protected> class <class name>{
|
// <public/private/protected> class <class name>{
|
||||||
// //data fields, constructors, functions all inside.
|
// //data fields, constructors, functions all inside.
|
||||||
// //functions are called as methods in Java.
|
// //functions are called as methods in Java.
|
||||||
// }
|
// }
|
||||||
|
|
||||||
public class Bicycle
|
public class Bicycle
|
||||||
{
|
{
|
||||||
// Bicycle's Fields/Variables
|
// Bicycle's Fields/Variables
|
||||||
public int cadence; // Public: Can be accessed from anywhere
|
public int cadence; // Public: Can be accessed from anywhere
|
||||||
private int _speed; // Private: Only accessible from within the class
|
private int _speed; // Private: Only accessible from within the class
|
||||||
protected int gear; // Protected: Accessible from the class and subclasses
|
protected int gear; // Protected: Accessible from the class and subclasses
|
||||||
internal int wheels; // Internal: Accessible from within the assembly
|
internal int wheels; // Internal: Accessible from within the assembly
|
||||||
string name; // default: Only accessible from within this class
|
string name; // default: Only accessible from within this class
|
||||||
|
|
||||||
// readonly values are set at run time
|
// readonly values are set at run time
|
||||||
// they can only be assigned upon declaration or in a constructor
|
// they can only be assigned upon declaration or in a constructor
|
||||||
readonly bool hasCardsInSpokes = false; // read-only private
|
readonly bool hasCardsInSpokes = false; // read-only private
|
||||||
|
|
||||||
// Constructors are a way of creating classes
|
// Constructors are a way of creating classes
|
||||||
// This is a default constructor
|
// This is a default constructor
|
||||||
public Bicycle()
|
public Bicycle()
|
||||||
{
|
{
|
||||||
gear = 1;
|
gear = 1;
|
||||||
cadence = 50;
|
cadence = 50;
|
||||||
_speed = 5;
|
_speed = 5;
|
||||||
name = "Bontrager";
|
name = "Bontrager";
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is a specified constructor (it contains arguments)
|
// This is a specified constructor (it contains arguments)
|
||||||
public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes)
|
public Bicycle(int startCadence, int startSpeed, int startGear,
|
||||||
{
|
string name, bool hasCardsInSpokes)
|
||||||
this.gear = startGear;
|
{
|
||||||
this.cadence = startCadence;
|
this.gear = startGear;
|
||||||
this._speed = startSpeed;
|
this.cadence = startCadence;
|
||||||
this.name = name;
|
this._speed = startSpeed;
|
||||||
this.hasCardsInSpokes = hasCardsInSpokes;
|
this.name = name;
|
||||||
}
|
this.hasCardsInSpokes = hasCardsInSpokes;
|
||||||
|
}
|
||||||
// Constructors can be chained
|
|
||||||
public Bicycle(int startCadence, int startSpeed) :
|
// Constructors can be chained
|
||||||
this(startCadence, startSpeed, 0, "big wheels", true)
|
public Bicycle(int startCadence, int startSpeed) :
|
||||||
{
|
this(startCadence, startSpeed, 0, "big wheels", true)
|
||||||
}
|
{
|
||||||
|
}
|
||||||
// Function Syntax:
|
|
||||||
// <public/private/protected> <return type> <function name>(<args>)
|
// Function Syntax:
|
||||||
|
// <public/private/protected> <return type> <function name>(<args>)
|
||||||
// classes can implement getters and setters for their fields
|
|
||||||
// or they can implement properties
|
// classes can implement getters and setters for their fields
|
||||||
|
// or they can implement properties
|
||||||
// Method declaration syntax:
|
|
||||||
// <scope> <return type> <method name>(<args>)
|
// Method declaration syntax:
|
||||||
public int getCadence()
|
// <scope> <return type> <method name>(<args>)
|
||||||
{
|
public int getCadence()
|
||||||
return cadence;
|
{
|
||||||
}
|
return cadence;
|
||||||
|
}
|
||||||
// void methods require no return statement
|
|
||||||
public void setCadence(int newValue)
|
// void methods require no return statement
|
||||||
{
|
public void setCadence(int newValue)
|
||||||
cadence = newValue;
|
{
|
||||||
}
|
cadence = newValue;
|
||||||
|
}
|
||||||
// virtual keyword indicates this method can be overridden
|
|
||||||
public virtual void setGear(int newValue)
|
// virtual keyword indicates this method can be overridden
|
||||||
{
|
public virtual void setGear(int newValue)
|
||||||
gear = newValue;
|
{
|
||||||
}
|
gear = newValue;
|
||||||
|
}
|
||||||
public void speedUp(int increment)
|
|
||||||
{
|
public void speedUp(int increment)
|
||||||
_speed += increment;
|
{
|
||||||
}
|
_speed += increment;
|
||||||
|
}
|
||||||
public void slowDown(int decrement)
|
|
||||||
{
|
public void slowDown(int decrement)
|
||||||
_speed -= decrement;
|
{
|
||||||
}
|
_speed -= decrement;
|
||||||
|
}
|
||||||
// properties get/set values
|
|
||||||
// when only data needs to be accessed, consider using properties.
|
// properties get/set values
|
||||||
// properties may have either get or set, or both
|
// when only data needs to be accessed, consider using properties.
|
||||||
private bool _hasTassles; // private variable
|
// properties may have either get or set, or both
|
||||||
public bool hasTassles // public accessor
|
private bool _hasTassles; // private variable
|
||||||
{
|
public bool hasTassles // public accessor
|
||||||
get { return _hasTassles; }
|
{
|
||||||
set { _hasTassles = value; }
|
get { return _hasTassles; }
|
||||||
}
|
set { _hasTassles = value; }
|
||||||
|
}
|
||||||
private int _frameSize;
|
|
||||||
public int FrameSize
|
private int _frameSize;
|
||||||
{
|
public int FrameSize
|
||||||
get { return _frameSize; }
|
{
|
||||||
// you are able to specify access modifiers for either get or set
|
get { return _frameSize; }
|
||||||
// this means only Bicycle class can call set on Framesize
|
// you are able to specify access modifiers for either get or set
|
||||||
private set { _frameSize = value; }
|
// 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()
|
//Method to display the attribute values of this Object.
|
||||||
{
|
public override string ToString()
|
||||||
return "gear: " + gear +
|
{
|
||||||
" cadence: " + cadence +
|
return "gear: " + gear +
|
||||||
" speed: " + _speed +
|
" cadence: " + cadence +
|
||||||
" name: " + name +
|
" speed: " + _speed +
|
||||||
" cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") +
|
" name: " + name +
|
||||||
"\n------------------------------\n"
|
" cards in spokes: " + (hasCardsInSpokes ? "yes" : "no") +
|
||||||
;
|
"\n------------------------------\n"
|
||||||
}
|
;
|
||||||
} // end class Bicycle
|
}
|
||||||
|
} // end class Bicycle
|
||||||
// PennyFarthing is a subclass of Bicycle
|
|
||||||
class PennyFarthing : Bicycle
|
// PennyFarthing is a subclass of Bicycle
|
||||||
{
|
class PennyFarthing : Bicycle
|
||||||
// (Penny Farthings are those bicycles with the big front wheel.
|
{
|
||||||
// They have no gears.)
|
// (Penny Farthings are those bicycles with the big front wheel.
|
||||||
|
// They have no gears.)
|
||||||
// calling parent constructor
|
|
||||||
public PennyFarthing(int startCadence, int startSpeed) :
|
// calling parent constructor
|
||||||
base(startCadence, startSpeed, 0, "PennyFarthing", true)
|
public PennyFarthing(int startCadence, int startSpeed) :
|
||||||
{
|
base(startCadence, startSpeed, 0, "PennyFarthing", true)
|
||||||
}
|
{
|
||||||
|
}
|
||||||
public override void setGear(int gear)
|
|
||||||
{
|
public override void setGear(int gear)
|
||||||
gear = 0;
|
{
|
||||||
}
|
gear = 0;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} // End Namespace
|
} // End Namespace
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user