Open solomem opened 2 years ago
string name = "Jaes";
int number = 2;
float price = 3.99f;
console.writeline(name + "camping");
/*
*/
three line ///, this will auto create summary
Everything inside the class is available to the class. But the variables inside the method only for the method. but not for other methods in the class.
{
...
}
Can only reference static variables to static methods.
var aaFloat = 1.1; var bbString = "K";
int: return type
public static int Add(int num1, int num2)
{
return num1 + num2;
}
throw;
Throw error.
try
{
Console.WriteLine("Please enter a number!");
string userInput = Console.ReadLine();
int userInputAsInt = int.Parse(userInput);
Console.ReadKey();
}
catch (FormatException)
{
Console.WriteLine("Format Error.");
}
catch(Exception)
{
Console.WriteLine("General Exception");
}
System will catch a specific exception (FormatException etc) or catches a general exception (Exception) FormatException: string to int parse OverflowException: input for int type too long
Quick reference:
or we can get the exception from the IDE:
//pre increment/decrement
--num
++num
// increment/decrement
num++
num--
&&: AND operator
exp: True && False
||: OR operator
==
!=
Use it over the int.Parse ?
myString.Equals("stringValue1")
myInt == myInt2
using System;
namespace SwitchCaseStatement
{
internal class Program
{
static void Main(string[] args)
{
int age = 25;
switch (age)
{
case 25:
Console.WriteLine("you can enter the club");
break;
case 10:
Console.WriteLine("Too young to enter");
break ;
default:
Console.WriteLine("How old are you then??");
break;
}
Console.Read();
}
}
}
This can be replaced my the if statement easily.
using System;
namespace IfStatementShortcut
{
/// <summary>
/// condition ? first_expression : second_expression
/// condition has to be either true of false
/// The conditional operator is right - associative
/// The expression a ? b : c ? d: e
/// is evaluated as a ? b : (c ? d : e)
/// NOT AS (a ? b : c) ? d : e
/// The conditional operator cannot be overloaded
/// </summary>
internal class Program
{
static void Main(string[] args)
{
int temperature = -1;
string stateOfMatter;
stateOfMatter = temperature < 0 ? "Solid" : (temperature > 100 ? "Gas" : "Liquid");
Console.WriteLine(stateOfMatter);
Console.Read();
}
}
}
using System;
using System.Threading;
namespace LoopDemo
{
internal class Program
{
static void Main(string[] args)
{
//for (int counter = 1; counter < 100; counter += 3)
//{
// Console.WriteLine(counter + " is lower than 100.");
//}
//Console.Read();
//int counter2 = 1;
//do
//{
// Console.WriteLine(counter2 + " is lower than 100.");
// counter2++;
//}while(counter2 < 100);
int lengthOfText = 0;
string wholeText = "";
do
{
Console.WriteLine("Please enter the names:");
string nameOfAllFriend = Console.ReadLine();
int currentLength = nameOfAllFriend.Length;
lengthOfText += currentLength;
wholeText += nameOfAllFriend;
Console.WriteLine("Length of all text: {0}", lengthOfText);
} while (lengthOfText < 20);
Console.WriteLine("Thanks, that is it.");
Console.WriteLine("All names entered: " + wholeText);
Console.Read();
}
}
}
Continue will skip the current value, and evalue with the next value.
using System;
namespace BreakContinue
{
internal class Program
{
static void Main(string[] args)
{
for (int counter = 0; counter < 1000; counter++)
{
//Console.WriteLine(counter);
if (counter % 100 == 99)
{
Console.WriteLine("At {0}, we skip.", counter);
//break;
continue; // it will skip the current
}
//Console.WriteLine(counter);
}
}
}
}
member variable in the class are protected, and available within the class only. We have to make it publicly accessible in order to visit it.
class Human
{
//member variable
public string firstName;
public void IntroduceMyself()
{
Console.WriteLine("My first name is: {0}", firstName);
}
}
class Human
{
//member variable
private string firstName;
private string lastName;
// parameterized constructors
public Human(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void IntroduceMyself()
{
Console.WriteLine("My name is: {0} {1}", this.firstName, this.lastName);
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ClassDemo
{
class Human
{
//member variable
private string firstName;
private string lastName;
private string address;
private int age;
//
public Human()
{
Console.WriteLine("New Human constructor is called, and an object is created.");
}
// parameterized constructors
public Human(string firstName, string lastName, string address)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public Human(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public Human(string firstName, string lastName, string address, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public void IntroduceMyself()
{
if (this.age > 0 && this.firstName != null && this.lastName != null && this.address != null)
{Console.WriteLine("My name is: {0} {1}, {2} years old, and live in {3}", firstName, lastName, age, address); }
else if (this.age == 0 && this.firstName != null && this.lastName != null && this.address != null)
{
Console.WriteLine("My name is: {0} {1}, and live in {2}", firstName, lastName, address);
}
else if (this.age == 0 && this.firstName != null && this.lastName != null && this.address == null)
{
Console.WriteLine("My name is: {0} {1}.", firstName, lastName);
}
else
{
Console.WriteLine("No user details provided");
}
}
}
}
\\ then in the main method
using System;
namespace ClassDemo
{
internal class Program
{
static void Main(string[] args)
{
Human denis = new Human("Denis", "Suals");
denis.IntroduceMyself();
Human abdule = new Human("Abdule", "Abdular", "101 MT");
abdule.IntroduceMyself();
Human jack = new Human("Jack", "Murphy", "99 Lucky St", 100);
jack.IntroduceMyself();
//Human micheal = new Human();
//micheal.IntroduceMyself();
Human BasicHuman = new Human();
BasicHuman.IntroduceMyself();
}
}
}
quick way to create property in vs:
type prop tab tab
// way 1
public int MyProperty { get; set; }
// way 2
//getter
public int GetLength()
{
return this.length;
}
public void SetLength(int length)
{
if (length < 0)
{
throw new ArgumentException("The length shall be a positive number");
}
this.length = length;
}
// way 3
public int Height
{
get { return this.height; }
set { this.height = value > 0 ? value : -value; }
}
// Usage:
using Newtonsoft.Json;
namespace My.Function.Models
{
public class Metadata
{
[JsonProperty(PropertyName = "image_id")]
public string ImageID { get; set; }
{
}
// in the main function, we access Box class
Box box = new Box();
Console.WriteLine("We are setting the length of the box to a different value.");
box.SetLength(5);
box.Height = 10;
box.Width = -3;
box.DisplayInfo();
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Members
{
class Members
{
// member - private field
private string memberName;
private string jobTitle;
private int salary = 2000;
// member - public field
public int age;
// member - property (Starts with a capital letter)
public string JobTitle { get { return jobTitle; } set { jobTitle = value; } }
// public member - exposes jobTitle safely from other classes
public void Introducing(bool isFriend)
{
if(isFriend)
{
SharingPrivateInfo();
}
else
{
Console.WriteLine("{0}, {1}, {2}, {3}", JobTitle, age, salary, memberName);
}
}
// constructor
public Members()
{
age = 30;
memberName = "Jack";
jobTitle = "Developer";
salary = 60000;
Console.WriteLine("Object created");
}
// member - finalizer - destructor
// ONLY ONE DESTRUCTOR IS ALLOWED
// CANNOT BE INHERENT
// CANNOT BE CALLED
// code is executed then the object is out of scope
~Members()
{
Console.WriteLine("Deconstruction of Member.");
}
private void SharingPrivateInfo()
{
Console.WriteLine("My salary is {0}", salary);
Debug.WriteLine("Debugging for the destruction member object");
}
}
}
Debug
using System;
namespace Arrays
{
internal class Program
{
static void Main(string[] args)
{
int[] grades = new int[5];
grades[0] = 1;
grades[1] = 2;
grades[2] = 3;
grades[3] = 4;
grades[4] = 5;
Console.WriteLine("Before: " + grades[0]);
Console.WriteLine("Please input the grade[0] value: ");
string input = Console.ReadLine();
int.TryParse(input, out grades[0]);
Console.WriteLine("After: " + grades[0]);
//Console.Read();
// another way of initializing an array
int[] gradeOfMathStudentA = { 20, 21, 23, 90, 13 };
// third way
int[] gradeOfMathStudenB = new int[] { 12, 85, 69, 309, 47, 86 };
for (int i = 0; i < gradeOfMathStudentA.Length; i++)
{
Console.WriteLine(gradeOfMathStudentA[i]);
}
// or
int counter = 0;
foreach(int k in gradeOfMathStudentA)
{
Console.WriteLine("Accessing using foreach {0} {1} vs {2}", k, gradeOfMathStudentA[counter], counter++);
}
Console.Read();
}
}
}
var result = str.Split(',')[1];
var result = str.Split(',').Skip(1).FirstOrDefault();
public void LoadJson()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
}
}
public class Item
{
public int millis;
public string stamp;
public DateTime datetime;
public string light;
public float temp;
public float vcc;
}
Without declearing the item"
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
{"Messages":[[{"message":"example message"}]]}
public class ErrorMessage
{
[JsonProperty("message")]
public string Message;
}
public class ErrorMessages
{
public List<List<ErrorMessage>> Messages;
}
name = name.TrimEnd('\').Remove(name.LastIndexOf('\') + 1);
public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
{
public void Add(K key, T addObject)
{
if(!ContainsKey(key)) Add(key, new List<T>());
if (!base[key].Contains(addObject)) base[key].Add(addObject);
}
}
// and to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", 23);
myDicList.Add("ages", 32);
myDicList.Add("ages", 18);
myDicList.Add("salaries", 80000);
myDicList.Add("salaries", 110000);
myDicList.Add("accountIds", 321123);
myDicList.Add("accountIds", 342653);
Nested Instance:
public class NestedMultiDimDictList<K, K2, T>:
MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
public void Add(K key, K2 key2, T addObject)
{
if(!ContainsKey(key)) Add(key,
new MultiDimDictList<K2, T>());
if (!base[key].Contains(key2))
base[key].Add(key2, addObject);
}
}
string msg = $"{doc.image_id}; {doc.uri}; {doc.labels}";
string msg1 = Regex.Replace(msg, @"\t|\n|\r|\n?|\s+", "").Replace(" ", String.Empty);
static async Task<string> PrepareCupsAsync(int numberOfCups)
{
Task[] eachCupTask = Enumerable.Range(1, numberOfCups).Select(index =>
{
Console.WriteLine($"Taking cup #{index} out.");
Console.WriteLine("Putting tea and sugar in the cup");
return Task.Delay(3000);
}).ToArray();
await Task.WhenAll(eachCupTask);
Console.WriteLine("Finished preparing the cups");
return "cups";
}
public static void WriteLineWithCurrentThreadId(string textToPrint)
=> Console.WriteLine($"Thread #{Thread.CurrentThread.ManagedThreadId} | {textToPrint}");
}
private static IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(@"appSettings.json", optional: false, reloadOnChange: true);
Assembly is a precompiled .NET code which can be run by the CLR. (single unit of depoyment, can be run directly by CLR)
Class library
Create the DLL once, and add referene to the applications.
Assembly runs on its own memory address. DLL needs a hoster, and consumed by the address space for the application.
For example:
TestClassRemoting test = (TestClassRemoting)Activator.GetObject(someType,someString);
THat's an explicit cast - you're telling the code to cast the Object returned from Activator.GetObject
to a type of TestClassRemoting
Cast syntax (T)expr
is used for many different conversions. The conversion from object
to TestClassRemoting
is an explicit reference conversion. TestClassRemoting
is a class (reference type) whose base class, or base class of base class etc., is object
. The C# compiler sees that the expression has compile-time type object. The cast tells the compiler that the actual type (run-time type) is really TestClassRemoting
(or some derived type). This is a downcast. The conversion in the opposite direction, from TestClassRemoting to object, is an implicit one. That is an upcast.
Animal animal = new Cat();
Bulldog b = (Bulldog) animal; // if (animal is Bulldog), stat.type(animal) is Bulldog, else an exception
b = animal as Bulldog; // if (animal is Bulldog), b = (Bulldog) animal, else b = null
animal = null;
b = animal as Bulldog; // b == null
using System;
using System.Collections.Generic;
namespace ListOfObjects
{
internal class Program
{
static void Main(string[] args)
{
List<Player> players = new List<Player>();
Player player1 = new Player("Chad");
Player player2 = new Player("Isaa");
Player player3 = new Player("Ka");
players.Add(player1);
players.Add(player2);
players.Add(player3);
foreach (Player player in players)
{
Console.WriteLine($"Name of player: {player}");
}
}
}
class Player
{
public string username;
public Player(string username)
{
this.username = username;
}
public override string ToString()
{
return username;
}
}
}
User input is always a string
double a = 3.14;
int b = Convert.ToInt32(a);
int c = 123;
double d = Convert.ToDouble(c);
int e = 21;
string f = Convert.ToString(e);
string g = "%";
char h = Convert.ToChar(g);
string j = "true";
bool i = Convert.ToBoolean(j);
Random random = new Random();
int num = random.Next() // random integer
int num = random.Next(1, 7);
double num = random.NextDouble(); / 0 ~ 1
if no return, then:
{... }
or if returns double:
static double methodName(int a, double b)
{...
return c;
}
Enable a single method to access multiple arguments
using System;
namespace paramsKeywords
{
internal class Program
{
static void Main(string[] args)
{
double total = CheckOut(3.99, 5.75, 15);
Console.WriteLine(total );
Console.ReadKey();
}
static double CheckOut(params double[] prices)
{
double total = 0;
foreach(double price in prices)
{
total += price;
}
return total;
}
}
}
Static = modified to declare a static number which belongs to the class itself rather than to any specific object
using System;
namespace StaticTutorial
{
internal class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Mustang");
Car car2 = new Car("Corvette");
//Console.WriteLine(car1.numberOfCars); // cannot be access like this
//Console.WriteLine(car2.numberOfCars); // cannot be access like this
Console.WriteLine(Car.numberOfCars);
}
}
class Car
{
string model;
public static int numberOfCars; // no object takes ownership of this member
public Car(string model)
{
this.model = model;
numberOfCars++;
}
}
}
Static method is not instantiatable.
Like Math
.
Math.Round()
Cannot do Math math1 = new Math()'
Technique to create multiple constructors with a different set of parameters. Name + parameters = signature.
1 or more child classes recieving fields, methods, etc from a common parent
using System;
using System.Reflection.Emit;
using System.Threading;
namespace InheritanceTutorial
{
internal class Program
{
static void Main(string[] args)
{
Car car1 = new Car();
Bicycle bike1 = new Bicycle();
Boat boat1 = new Boat();
car1.speed = 12;
bike1.speed = 9;
boat1.speed = 3;
Console.WriteLine(car1.wheels);
}
}
class Vehicle
{
public int speed { get; set; }
public void go ()
{
Console.WriteLine("This vehicle is moving");
}
}
class Car: Vehicle
{
public int wheels = 4;
}
class Bicycle: Vehicle
{
public int wheels = 2;
}
class Boat : Vehicle
{
public int wheels = 0;
}
}
Precede class with abstract to prevent user from creating the object from the abstract class.
using System;
namespace arrayOfObjects
{
internal class Program
{
static void Main(string[] args)
{
Car[] garage = new Car[3];
Car car1 = new Car("car1");
Car car2 = new Car("car2");
Car car3 = new Car("car3");
garage[0] = car1;
garage[1] = car2;
garage[2] = car3;
Console.WriteLine(garage[0].model);
foreach (Car car in garage)
{
Console.WriteLine(car.model);
}
Car[] new_garage = { new Car("car4"), new Car("car5"), new Car("car6") };
foreach (Car car in new_garage)
{
Console.WriteLine(car.model);
}
}
}
class Car
{
public string model;
public Car (string model)
{
this.model = model;
}
}
}
using System;
namespace objectAsArgumentTutorial
{
internal class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Mustang", "red");
Console.WriteLine("Original color: " + car1.color);
// to change the color
ChangeColor(car1, "black");
Console.WriteLine("Changed color: " + car1.color);
Car car2 = Copy(car1);
Console.WriteLine(car2.model + " " + car2.color);
}
public static void ChangeColor(Car car, String color)
{
car.color = color;
}
// copy the car object
public static Car Copy(Car car)
{
return new Car(car.model, car.color);
}
}
class Car
{
public String model;
public String color;
public Car(String Model, String Color)
{
this.model = Model;
this.color = Color;
}
}
}
using System;
namespace methodOverriding { internal class Program { static void Main(string[] args) { // method overriding: - provides a new version of a method inherited from a parent class // -inherited method must be: abstract, virtual, or already overriden // - Used with ToString(), polymorphism
Dog dog = new Dog();
Cat cat = new Cat();
dog.Speak();
cat.Speak();
}
}
class Animal
{
// a virtual method states it can be overrided.
public virtual void Speak()
{
Console.WriteLine("From the base method: I am the origin animal.");
}
}
class Dog: Animal
{
public override void Speak()
{
base.Speak(); // access to the base class
Console.WriteLine("Overriden: I am now born as a dog");
}
}
class Cat : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("Overriden: I am not an cat god.");
}
}
}
Used to modify and display any string representation of an object
using System;
namespace ToStringMethod
{
internal class Program
{
static void Main(string[] args)
{
// ToString() = converts an object to its string representation so that it is suitable for display.
Car car = new Car("Chevy", "Corvette", 2022, "Blue");
Console.WriteLine(car);
Console.ReadKey();
}
}
class Car
{
String make;
String model;
int year;
String color;
public Car(string make, string model, int year, string color)
{
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
public override string ToString()
{
//return base.ToString();
String msg = "This is a " + make + " " + model;
return msg;
}
}
}
using System;
namespace polymorphism { internal class Program { static void Main(string[] args) { Car car = new Car(); Boat boat = new Boat(); Bicycle bike = new Bicycle();
Vehicle[] vehicles = {car, boat, bike};
foreach (Vehicle vehicle in vehicles)
{
vehicle.Go();
}
}
}
class Vehicle
{
public virtual void Go() { }
}
class Car: Vehicle
{
public override string ToString()
{
return "I am a car";
}
public override void Go()
{
Console.WriteLine("The car is moving..");
}
}
class Boat: Vehicle
{
public override void Go()
{
Console.WriteLine("The boat is moving..");
}
public override string ToString()
{
return "I am a boat";
}
}
class Bicycle : Vehicle
{
public override string ToString()
{
return "I am a bike";
}
public override void Go()
{
Console.WriteLine("The bike is moving..");
}
}
}
// Interface defines a "contract" that all the classes inheriting from should follow
using System;
using System.Reflection;
namespace InterfaceTutorial { internal class Program { /*
// Interface defines a "contract" that all the classes inheriting from should follow
BENEFIT = security + multiple inheritance + "plug and play"
*/ static void Main(string[] args) { Rabbit rabbit = new Rabbit(); rabbit.Flee();
Hawk hawk = new Hawk();
hawk.Hunt();
Fish fish = new Fish();
fish.Flee();
fish.Hunt();
}
interface IPrey { void Flee(); }
interface IPredator { void Hunt(); }
class Rabbit : IPrey { public void Flee() { Console.WriteLine("The rabbit runs away!"); } }
class Hawk : IPredator { public void Hunt() { Console.WriteLine("The hawk is hunting for rabbits."); } }
// multiple interface class Fish: IPredator, IPrey { public void Flee() { Console.WriteLine("The fish swims away."); }
public void Hunt()
{
Console.WriteLine("The fish is searching for food.");
}
}
} }
One file per class!