solomem / C-

0 stars 0 forks source link

C# introduction #3

Open solomem opened 2 years ago

solomem commented 2 years ago

image

image

One file per class!

solomem commented 2 years ago

string name = "Jaes";
int number = 2;
float price = 3.99f;

console.writeline(name + "camping");
solomem commented 2 years ago

Multiple line comments

/*

*/
solomem commented 2 years ago

class summary

three line ///, this will auto create summary image

solomem commented 2 years ago

Scope

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 overwirte the variable in diffferent scope

image

solomem commented 2 years ago

Can only reference static variables to static methods.

solomem commented 2 years ago

implicitly define a variable

var aaFloat = 1.1; var bbString = "K";

solomem commented 2 years ago

method

image image

int: return type

        public static int Add(int num1, int num2)

        {
            return num1 + num2;
        }
solomem commented 2 years ago

Exception

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: image

or we can get the exception from the IDE: image

solomem commented 2 years ago

Operator

//pre increment/decrement
--num
++num
// increment/decrement
num++
num--

&&: AND operator 
exp: True && False

||: OR operator

==
!=
solomem commented 2 years ago

if statement

image image

solomem commented 2 years ago

TryParse

Use it over the int.Parse ? image image image image

float

image

double

fail (string not a number-like)

image

image

image

solomem commented 2 years ago

Compare values:

String

myString.Equals("stringValue1")

int

myInt == myInt2

solomem commented 2 years ago

Switch & Case

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.

solomem commented 2 years ago

if statement : shortcut (lambda like fashion)

image

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();

        }
    }
}
solomem commented 2 years ago

Loops

image

image

image

image

image

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();
        }
    }
}
solomem commented 2 years ago

Break & Continue

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);
            }    
        }
    }
}
solomem commented 2 years ago

OOP in C

image

image

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);
        }
    }

constructors

    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);
        }
    }

Multiple Constructors

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();
        }
    }

}

properties

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();
solomem commented 2 years ago

Members

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");
        }
    }
}

Destructor and Debug

image

solomem commented 2 years ago

1D Array

image

image

foreach with 1D Array

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();
        }
    }
}
solomem commented 1 year ago

string split

var result = str.Split(',')[1];

var result = str.Split(',').Skip(1).FirstOrDefault();

solomem commented 1 year ago

parse json file

    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);
    }
solomem commented 1 year ago

deseriaze json

{"Messages":[[{"message":"example message"}]]}

public class ErrorMessage
{
    [JsonProperty("message")]
    public string Message;
}

public class ErrorMessages
{
    public List<List<ErrorMessage>> Messages;
}
solomem commented 1 year ago

String split remove last one

name = name.TrimEnd('\').Remove(name.LastIndexOf('\') + 1);

solomem commented 1 year ago

multidimensionallist

   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);
       }    
}
solomem commented 1 year ago

regrex remove strings

string msg = $"{doc.image_id}; {doc.uri}; {doc.labels}";
string msg1 = Regex.Replace(msg, @"\t|\n|\r|\n?|\s+", "").Replace(" ", String.Empty);
solomem commented 1 year ago

LINQ: IEnumerable of Tasks.

        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";
        }
solomem commented 1 year ago

Thread

public static void WriteLineWithCurrentThreadId(string textToPrint)
                  => Console.WriteLine($"Thread #{Thread.CurrentThread.ManagedThreadId} | {textToPrint}");
    }
solomem commented 1 year ago

configure builder

private static IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(@"appSettings.json", optional: false, reloadOnChange: true);
solomem commented 1 year ago

Assembly?

Assembly is a precompiled .NET code which can be run by the CLR. (single unit of depoyment, can be run directly by CLR)

image

DLL?

Class library

image

image

Create the DLL once, and add referene to the applications.

Difference Assembly vs DLL?

Assembly runs on its own memory address. DLL needs a hoster, and consumed by the address space for the application.

solomem commented 1 year ago

generics in c

image

https://stackoverflow.com/questions/9857180/what-does-t-denote-in-c-sharp image

solomem commented 1 year ago

Type conversion

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
solomem commented 1 year ago

overwrite ToString method

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;
        }
    }
}
solomem commented 1 year ago

Escape Sequence

image

solomem commented 1 year ago

declaration and initialization

image

solomem commented 1 year ago

constant

image

solomem commented 1 year ago

Casting

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); 
solomem commented 1 year ago

user input

solomem commented 1 year ago

Random number

Random random = new Random();
int num = random.Next() // random integer
int num = random.Next(1, 7);

double num = random.NextDouble(); / 0 ~ 1
solomem commented 1 year ago

method return value

if no return, then:

{... }

or if returns double:

static double methodName(int a, double b)
{...
return c;
}
solomem commented 1 year ago

params keyword

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;
        }
    }

}
solomem commented 1 year ago

Static (method, variable)

variable

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++;
        }
    }
}

method

Static method is not instantiatable. Like Math. Math.Round() Cannot do Math math1 = new Math()'

solomem commented 1 year ago

Overloaded Constructors

Technique to create multiple constructors with a different set of parameters. Name + parameters = signature.

solomem commented 1 year ago

inheritance

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;
    }
}
solomem commented 1 year ago

Abstract class

Precede class with abstract to prevent user from creating the object from the abstract class.

image

solomem commented 1 year ago

array of objects

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;
        }   
    }
}
solomem commented 1 year ago

pass objects

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;
        }

    }
}
solomem commented 1 year ago

Method overriding:

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.");
    }

}

}

solomem commented 1 year ago

ToString() Method (override the ToString() method in any class)

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;
        }
    }
}
solomem commented 1 year ago

Polymorphism (method override, class inherient)

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..");
    }
}

}

solomem commented 1 year ago

Interface

// Interface defines a "contract" that all the classes inheriting from should follow

namespace InterfaceTutorial { internal class Program { /*