C#/Visual Studio/Visual Studio Code -Concepts and Fundamentals

¡Supera tus tareas y exámenes ahora con Quizwiz!

Ref/Out

-Ref&Out are both ways to pass references to a variable -not recommended for frequent use *OUT*-modifier[on params] - modifier we use when we declare a funciton -different way a method can be called -method declares parameter with out ex void OutArgExample(out in number) { number = 44; } int initializeMethod; OutArgExample(out initiliazeMethod); Console.Writeline(initializeMethod) **REF** -ref keyword passes arguments by reference -ref basically manipulates the value of variable it wraps when called; the variable is now different in the call and independently of ref wrapper **OUT** -also passes arguments by reference. but startts by initializing param value, whereas ref would use the field's own value to start with(doesnt have to initialize a value)

Logger

-Set a target -Set a rule -The package reference needs to be in the nlog config file, we need to make sure that all the packages are downloaded and written in th <packageReference> -Logging implementation is something that a class may need

There are two types of Fields:

-String fields -Decimal Fields

Statements = Declaration -> initialization[examples] -as well as value(primitive) types examples

-These are actually all object of classes int integer = 0[int=declaration;(integer=0):initialization short sixteenbit = 0 long sixtyfoutbit = 0; byte eightbit = 0; float thirtytwobit = 0//decimal double sixtyfoutbit = 0;//decimal(higher precision decimal bit128 = o//highest precision declaration;good for dealing with currency(dependable) bool trueorfalse = true; string name = "name";

terminal used to compile C#?

-We compile C# via git bash terminal or the cmd

What are Strings?

-a string is an object of type String whose value is text -internally, the text is stored as a sequential read-only collection of Char objects -Immutable Unicode

Abstract Base-Field:

-an abstract class can have an instance field in it -the derived class can access this field through "base" -key difference between abstract class and interface

INTERFACES:

-an interface contains only the signatures of methods, properties, events or indexers -a class or struct that implements the interface must implement *all* members of the interface(like abstracts) that are specified in the interface definition -an interface can inherit from one or more base interfaces; but class can only inherit from one class, abstract or not []when a base type list contains a base class and interface, the base class must come first in the list -interfaces cant contain constants, fields , operators, instance constructors, finalizers or types -interface members are automatically public, and they cant include any access modifiers ; -members cant be static -A class can inherit a base class and also implementone or more interfaces

Boxing/Unboxing

-boxing is process of converting value type to the type object or any interface type implemented by this value type -Following ex, int vari i is boxed and assigned to object: int i = 123; object o =i;//o now has type object The object o can then be unboxed and assigned to integer variable i: o = 123; int j = (int)o;//unboxin' Another EXAMPLE: List<object> mixedList = new List<object>();//boxed in object sum += (int)mixedList[j] * (int)mixedList[j];//(int) unboxes Extra info: the original value type and the boxed object use separate memory locatoins, and therefore can store different values

what are objects?

-collection of data and behavior -Every object is going to be an instance of a class. --a class is going to define the behavior of that object

What is a Constructor?

1-A constructor in Java is a block of code, similar to a method, that is called when an instance of an object is created Differences between constructor and method: -constructor doesn't have a return type so dont expect an operation to be performed -name of constructor must be the same as the name of the class -unlike methods, constructors cannot be abstract, final, native, static, or synchronized example: public class Platypus{ String name; Platypus(String input){ name = input; } Platypus(){ this("John/Mary Doe"); } } -so, in the code above, there are two constructors. The first takes a String input to . name the instance. -The second constructor, taking no parameters, calls the first constructor by the default name "John/Mary Doe" -Default Constructor: executes/copies any fields or properties in the base-class

Describe difference between Array and Array list

1-Array is basic functionality provided by the core Java programming language; ArrayList comes from a collection framework in Java 2-array members are accessed using '[ ]', while arrayList has a set of methods for accessing and modifying elements 3-Main difference: array is a fixed sixed data structure; arrayList, you never have to specify the size while creating its object; even if you do, you can always add more elements 4-array can contain primitive data types as well as objects of classes(depending on def of array;arrayList only supports object entries, not primitive data types example 1(array): int[] arr = new int[2]; arr[0] = 1; arr[1] = 2; System.out.println(arr[0]) example2(arrayList must be imported first): ArrayList<Integer> arrL = new ArrayList<Integer>(2); // Add elements to ArrayList arrL.add(1); arrL.add(2); // Access elements of ArrayList System.out.println(arrL.get(0));

What is an exception?

1-Exceptions Handling in Java 2-Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions(e.g. divide by zero, array access out of bounds). 3-In Java, an exception is an object that wraps an error event that occurred within a method and contains: -Information about the error including its type -the stage of the program when the error occurred 4-Exception objects can be thrown and caught 5-Exceptions are used to indicate many different types of error conditions -JVM Errors:OutOfMemoryError -System Errors:FileNotFoundException -Programming Errors:NullPointerException 6-Exceptions separate error handling code from regular code 7-Exceptions propogate errors up the call stack 8-Exceptions classes group and differentiate error types

What is a method?

1-METHODS: have return capabilities. also can have names different from that of class 2-Methods are a collection of statements that are grouped together to perform an operation. When you call the System.Console.WriteLine() method, for example, the system actually executes several statements in order to display a message on the console

Why doesn't Java support multiple inheritances?

1-The reason why Java supports multiple interfaces but not multiple inheritances is because interfaces simply specify 'what' the class is doing(run(),cook(),fly()), not how(runSpeed=?,bakingTime=?,flightCoordinates=?). 2-Multiple inheritances are a problem because two classes may define different ways of doing the same thing, and the subclasses wont be able to choose which one to pick 3- if you have two parent classes, they might have different implementations of the same feature. possibly two different features..with the same name

Why are strings immutable?

1-They are immutable because you cannot change the object itself; you can change the value of the variable, but not the object-literal 2-in Java once an instance has been created or initialized, the information within cannot be modified, immutable classes 3-string pools have one shared value and if you could modify value of object for one vari, that would cause all the other vari's (of similar values) value to change. JVM saves time by refferring to string pool to see if new object is already stored in string pool and points vari to string if already there 3.5-Java is weird and a little counter-intuitive

What is an interface?

1-a reference type in Java. 2-similar to a class. 3-a collection of abstract methods 4-A class implements an interface, thereby inheriting the methods of the interface 5-writing an interface is similar to writing a class, but a class describes the attributes of an object; an interface contains behaviors that a class implements(they're like rules that need a class to be carried out) 6-Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class 7-you cannot instantiate an interface 8-the interface keyword is used to declare an interface 8.5-variables in interfaces are final, public, and static example:

static keyword facts:

1-applicable to classes, nested classes, variables, methods, and blocks 2-when a class member is declared static, it becomes global for all other members of the class 3-all objects share same copy of static member 4-static member can be used independently of any object of the class 5-can access the static member of the class before its object is created 6-best example of static member is main(). declared static so it can be invoked before any object is created. 7-static method can only call other static methods; static methods can only access static data 8-static block is executed only once when the class is loaded. Used to initialize the static variables of the class

What is the difference between final and static?

1-final and static are both keywords in Java 2-the static keyword is applicable to nested static classes, methods, variables and blocks. Final keyword is applicable to classes, methods, and variables 3-a static variable can be initialized anytime whereas a final variable must be initialized at the time of declaration 4-a static variable can be reinitialized whereas a final variable, once initialized, can never be reinitialized 5- a static method can access the static member of the class and can only be invoked by the other static methods. A final method can never be inherited by any class 6-static block is used to initialize the static variable whereas final keyword does not support any block

What is an Object?

1-in Object-Oriented-programming, an object is the instance of a class where the object can be a combination of variables functions and data structures 3-example from Java: // Class Declaration public class Dog { // Instance Variables String name; String breed; int age; String color; // Constructor Declaration of Class public Dog(String name, String breed, int age, String color) { this.name = name; this.breed = breed; this.age = age; this.color = color; }

Overloading vs. Overriding(plus defs)

1-overriding: means having two methods with the same method name and parameters IN TWO DIFFERENT CLASSES(parent and sub classes) 2-Overriding allows a child(sub) class to provide a specific implementation of a method that is already provided by its parent class 2.5-overriding is basically changing a functions originally(parent-class) defined purpose in the subclass(polymorphism) 3-Overloading occurs when two or more methods IN ONE CLASS have the same method name but different parameters(same function name with two different jobs polymorphism applies to overriding, not to overloading 4-overriding is a run-time concept while overloading is a compile-time concept

Signature

A method signature is the parameter and return type

What is a Struct:

A struct type is a value type that is typically used to encapsulate small groups of related variables,such as coordinates of a rect or the chars of an item in an inventory: public struct Book{ public decimal price; public string title; public string author; } -call it this way: Book HarryPotter = new Book();

Common Type System:

Each type in the CTS is defined either as a value type or a reference type -types defined using the struct keyword are value types; -types defined using the class keyword are reference types Value Types: -there are two categorires of value types: struct an enum -The built-in numeric types are struct, and they have propertied and ,ethods that we can access: byte b = Byte.MaxValue; *"Reference Types"* 1-A type that is defined as a class, delegate, array, or intereface is a reference type

Default Constructor

Every class has a default constructor -any fields or properties that have default value, that assignment is going to happen automatically in the default constructor --abstract classes dont have a constructor --if there is more than one constructor, the one who is going to be called is the one that matches the parameter types -one constructor can call another

Unicode

Expands the basic characters of our keyboard to tens of thousands of characters(different alphabets)

Assembly

For us assembly means the product for our first stage where we compile from our original file(source code), into that common intermediate language(MSIL) -The assembly contains the metadata that describes that code *a dll contains intermediate language, code and metadata[dll==Assembly]

implicit conversion of reference types(upcasting and Downcasting)

Giraffe g = new Giraffe(); Animal a =g; Heres how to cast back down: Giraffe g2 = (Giraffe) a;

Func/Action

So, whereas a delegate declares itself, then a method consumesand object of it and becomes a handler; the funct/action keywords takes those two lines of code and turns it into one Ex: delegate= delegate bool Comparer(string a ,string b); + Sort method that accepts delegate type Func way = Sort(Func<string,string,bool>Comparer) { } FUNC=takes in params, last one is return vlaue AWAIT = all params return void Example of Action Lambda: Action<int> displayHex = intValue => { Console.WriteLine(intValue.ToString("X")); };

Types(**important**)

VALUE Type-every variable of value type contains its value right there. Directly contains a value. They are not allowed to have sub-struct REFERENCE Type- when we have a reference variable that contains an object, I have a new reference to that object, it is the same object, not a copy. When we copy that variable, we copy that reference not the object itself. ENUMS type - an enum is a list of something. When we have some kind of something(bunch of colors, days of the week,etc), after we've defined the value of it in our source code, each value is a constant

What is LINQ?

[Language-Integrated Query-language] -name for a set of technologies based on the integration of query capabilities directly into the C# language -With LINQ, a query is a first-class language construct, just like classes, methods, events -queries are written in query expression ->which are written in a declarative "query syntax" -by using query syntax, u can perform filtering, ordering, and grouping operations on data sources and transform data in sql databases(hmmm..), ADO.NET Datasets,XML documents and streams, and .NET collections see ScriptingExamples for full example. <><>>><><<><><>< -a query is not executed until you iterate over the query variable, for example, in a foreach statement query expressions can be used to query and to transform data from any LINQ-enabled data source(ie.;a single query can retrieve data from a sql db and produce an XML stream as output) <<><><>>><. - most queries in LINQ are written using the LINQ declarative query syntax -bvut the query calls must be translated into method calls for the .NET common language runtime(CLR) when the code is compiled -These method calls invoke the standard query operators, which have the names: -Where -Select -GroupBy -Join -Max -Average Query Syntax : IEnumerable<int> numQuery1= from num in numbers where num % 2 == 0 orderby num select num; Method Syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n); foreach(int i in numQuery1) { Console.Write(i+ ""); } Console.WriteLine(System.Environment.NewLine); foreach (int i in numQuery2) { Console.Write(i + ""); } -the above use of Where and OrderBY are not actually apart of the built-in types we may be using in our method syntax; but because of extension methods we can implement them -for using LINQ, we have to know about how to bring extension methods into scope by using the correct "using" directives -Linq query expressions allow for stacked expressions independent of each other(kinda) -deferred execution of each method

an assembly is?

a unit of deployment for C#

Abstract vs Interfaces

abstract methods are better for having shared implementation across multiple classes -interfaces for all other types of shared types/signatures across multiple classes/members *POLYMORPHISM* -common 'way' to access different methods -implement abstraction

Scope

an indentifier's visibility determines the portions of the program in which it can be references-- its scope. -an identifier is visible(i.e., can be used) only in portions of a program encompassed by its 'scope', which may be limited(in order of increasing restrictiveness) to the file, function, block,or function prototype in which it appears. -the scope of an identifier is the of the program in which the name can be used. --This is sometimes called the 'lexical scope'. -There are four kinds of scope: --function --file --block --function prototype

built-in type/Custom Types:

built-in: long,double,int,short,char,string,decimal,float custom: -we use the struct, class, interface, and enum constructs to create our own custom types

explicit conversion(downcasting)

double x = 1234.4; int a; a = (int)x -the result of that conversion will be the loss of .4, but the value is now type int

Garbage Collection/Managed Code

for memory management. Garbage Collection-deallocates values on memory when they are not needed anymore Managed code-code thats run in the CLR gen0 gen1 gen2 -in gen0 the CLR checks for garbage very frequently(checks if object can be deallocated from memory[no longer being used or referenced]). If the object survives several checks, then it will go to gen1 and gen2, to be checked less -in gen2 it doesnt get checked as much

Example of For Loops:

for(int i = 0;i<10;i++) { Console.WriteLine(i); }

Example of Using foreach to iterate over array

foreach(var item in integerArray) { System.Console.WriteLine(item); } -try not to use foreach to delete items in an array

Example of Conditional

if (integer == 5) { Console.WriteLine("this is from an if statement! - "+integer); } else { Console.WriteLine("Does not equal 5!"); }

Properties with Backing Fields

if a property has a get accessor that returns a private field; and set accessor that performs some kind of validation, then it is an backing field: (SIngleton patterns?) public int hours { get{return seconds/3960;} set { if(value <0 ??value>24) cw=>"({0}must be between 0 and 24",nameof(value)); seconds=value*3960;//if value between 0 and 24 } }

Examples of if statement shorthand:

if(integer > 0) System.Console.WriteLine("if statement shorthand");

data types:

int integer = 0; short sixteenbit = 0; long sixtyfourbit = 0; byte eightbit = 0; float thirtytwobit = 0; -floating point for decimals double sixtyfourbitfloat = 0; -for high precision floats decimal bit128 = 0; -suitable for dealing with currencies(highest precision) char Character = 'A'; bool trueorfalse = true;

implicit Type Conversion:

int num =2133423; long bignum = num; so there's no loss of value with this conversion, because long holds int types plus more

Example of Integer Arrays

int[] integerArray = new int[10];//size 10/BUT YOU CANNOT CALL [10]-BECAUSE 0-INDEX integerArray[2] = 6;

Visual Studio

microsoft Visual Studio is an integrated development environment(IDE) from Microsoft. It is used to develop computer programs, as well as web sites, web apps, web services and mobile apps. Visual studio uses microsoft software development platforms such as Windows API, windows forms, windows presentation foundation, windows store and microsoft silverlight. It can produce both native code and managed code.

EVENTS/EVENT-HANDLERS see (refer to Day3 training Notes for good example)

my definition: an event is an initialization of a delegate with the "event" keyword; which makes it a...*special* delegate object...an event as practice: try explaining the example in caret(Day3TRAININGNOTES) <><><><><><>><>><>><><>>< **EVENTS** -events ENABLE A CLASS OR OBJECT TO NOTIFY OTHER CLASSES OR OBJECTS WHEN SOMETHING OF INTEREST OCCURS -The class that sends(or raises[or CAUSES]) the event is called the *publisher* and the classes that receive(or handle) the event are called the subscribers -In C# Windows Forms or Web apps, u subscribe to events raised by controls such as buttons and list boxes; you can use the EVENTS OVERVIEW: -the publisher determines when an event is raised;the subscribers INDIVIDUALLY determine what action is taken in response to the event -An event can have multiple subscribers.A subscriber can handle multiple events from multiple publishers -Events that have no subscribers are never raised(really?) -Events are typically used to signal user actions suchas button clicks or menu seletions in graphical user interfaces -When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised refer to caret example(Day3TRAININGNOTES) <><>>><><><><><<><> "SUBSCRIBING/UNSUBSCRIBING TO AN EVENT" -you subscribe to an event that is published by another class when you want to write custom code that is called when that event is raise[caused] -When all subscribers have unsubscribed from an event, the event instance in the publisher class is set to null.

Using "new" on Methods

never use new as a keyword for a method because you will lose all implementation inherited from base classes/abstracts/interfaces

Example of creating a public class in another script and making an object of it in a Main method:(CONSTRUCTOR EXAMPLE TOO)

public class Employee { //constructor public Employee() { name = "Nick"; } //fields public string name; public double salary; public decimal yearlySalary = 45000; //methods public decimal PaycheckAmount(decimal weeks) { return yearlySalary*(weeks/52); } } -in Main Method: Employee newEmployee = new Employee();

try/catch/finally example:

try { return DateTime.Now; } catch(System.Exception exx) { Console.WriteLine(exx.Message; throw new Exception('Unable to get current time") } Finally { cw=>"End of code" }

Example of try/catch/finally blocks

try{ integerArray[10] = 40; System.Console.WriteLine(integerArray[10]); } catch( IndexOutOfRangeException ex) { System.Console.WriteLine(ex.Message); } finally { //always runs after try and/or catch System.Console.WriteLine("\nThis msg shows as a result of finally block!\n"); }

Example of Ternary Statements:

var output = (integer < 6)? "less than 6" : "not less than 6";//more shorthand Console.WriteLine(output);

VS Code

vs code is a source code editor developed by Microsoft for windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring. It is free and open-source, although the official download is under proprietary license

Use LINQ in Visual Studio for:

(the tag-ons to List) List.Max() List.Sum() List.Average() -you can also incorporate lambda expression with these;you can work with lists/arrays using these

Local Function Declaration(Lambda Expression)

"=>"(lambda expression) -the lambda expression= a lambda expression can be simply viewed as a function or method without a name, which looks like the method parameter(s) => method body, or method param(s) => method return value. the => operator is called lambda operator and reads "go to"

SERIALIZATION/XML refer to Microsoft Doc for detailed example: https://docs.microsoft.com/en-us/dotnet/standard/serialization/examples-of-xml-serialization

"SERIALIZATION" -The process of converting an object into a stream of bytes(or json,xml, etc.) to store the object or transmit it to memory,a database or a file -its main purpose is to save the state of an object in order to be able to recreate it when needed xml example: <Name> <FirstName> Nick </FirstName> <LastName> Escalona </LastName> </Name> -the above is a serialization of the c# version: public class name { public string FirstName{get;set;} public string LastName { get; set; } } -usually c# saves all of this implementation for -serialization turns c# object into byte stream -deserialization turns some byte stream into c# form -other forms of serialization: JSON -creates a persistent state of an object "XML Serialization example":refer to caret Day4TrainingNotes "XML DeSerialization example":refer to caret Day4TrainingNotes

Extended Modifiers

**Static**-we can have this on classes, methods and properties. Instances of classes that have static members share the same variable(is not a copy of the variable, is like a reference of the variable/member). A static class is a class where all the members are static, its just a container for static methods and members. We cant instantiate or inherit from a static class. **Const**-the value is constant, you set it and you can never change it again. Once it is set it can not be changed **readonly**-similar to const but a little more flexible. You are allowed to set a read only variable in the contructor, but once you set it its locked in **Sealed**-means that you are not allowed to INHERIT from this class **Abstract** is one where we dont provide an implementation for the class **Virtual**-you are not allowed to override a METHOD unless its virtual **Override**-allows a subclass or child class to provide a specific/modified implementation of a method that is already provided by one of its super classes/parent classes **new**-it goes along with override, it declared a method like override. We can hide the parent method **partial class**-a class where you are allowed to move that class into more than one file. The definition will be merged together as if they where together **final**-it means that you cant make any extensions in that class(no inheritance) <><><><><><.OVERRIDE VD NEW (MODIFIER)<><><><><><><> -override modifier extends the base class method for modification, and the *new* modifier hides it

LAMBDA EXPRESSION AS ANONYMOUS FUNCTION refer to caret examples Day3TRAININGNOTES

*Delegates and named method* -in C#, a delegate definition can be viewed as a "method-type" definition (method signature) using lambda expression; delegates can become more streamlined: [*REMEMBER THIS*] Func<int,bool> isPositive = new Func<int,bool>(IsPositive); -BECOMES- Func<int,bool> isPositive = IsPositive <><><>><><>><>< EVEN FURTHER: -When the type of param can be inferred(like, from Func<int>,<bool>)the type declaration of param(int) can be omitted -when lambda expression has one parameter, the parentheses can be omitted -When the body of the lambda expression "has only one return" statement , the brackets and "return" keyword can be omitted So, the previous lambda expression can be rewritten as: Func<int,bool>isPositive =int32=>int32>0 -When having *more than one statement in the body*, the "brackets{} and return are required public static void StatementLambda() { Func<int,bool> isPositive = int32 => { Console.WriteLine(int32); return int32 > 0;//ok, because still only one return:bool } }

extension needed for C#?

-.cs

DAUFUQ are Fields???

-A FIELD IS A VARIof any type that is declared directly in a class or struct -Fields are members of their containg type -A class or struct may have instance fields (or static fields or both) -instance fields are specific to an instance of a type -If you have a class 'T', with an instance 'F', you can crearte two objects of type 'T', and modify the value of F in each object without affecting the value in the other object -should generally only use fields for variables that have private or protected accessibility -Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method: -A class that represents a calendar date might have three integer fields: one for month;one for day, and one for the year script example: //private field private DateTime date; //public field(not smart) public string day; //public property DateTime date { get { return date; } set { if (value.Year >1990 && value.Year <=DateTime.Today.Year) { date = value; } else { throw new ArgumentOut OfRangeException(); } } } //public method also exposes date field safely public void SetDate(string dateString) { DateTime dt = Convert.ToDateTime(dateString); // Set some reasonable boundaries for likely birth dates. if (dt.Year > 1900 && dt.Year <= DateTime.Today.Year) { date = dt; } else throw new ArgumentOutOfRangeException(); } -to access a field in an object, add a period after the object name, followed by the name of the field, as in "objectname.fieldname" example: CalendarEntry birthday = new CalendarEntry(); birthday.day = "Saturday -a field can be given an initial value this way: public string day = "Monday"

Lambda Expressions

-A lambda expression is a **syntax to create *delegates* or *expression-trees** -it is a very powerful syntactic sugar makingC# functional -at syntax level, a lambda expression can be simply viewed as a function or method without name(functional programming), which looks like: method param(s) => method body; method param(s) => method return value -The => operator is called Lambda Operator and basically reads: "Go To"

Reference Types

-A type that is defined as a class, delegate, array, or interface is a reference type -at runtime, when u declare a vari of a reference type, the vari contains the value of null until u explicitly create the object by using the new operator, or assign it an already made object Myclass mc = new Myclass(); -or- Myclass mc2 = mc;//null All ARRAYS R REFERENCE TYPES -derive from System.Array class -int[] nums = {1,2,3} int len = nums.Length So, basically, when you are declaring a string, int... you are referencing a class they derive from(System.string or wutever)

What is an Enum?

-An enum defines a set of NAMED INTEGRAL CONSTANTS -The System.IO.FileMode enumeration in the .NET class library contains a set of named integers that specify how a fil should be opened Example: public enum FileMode { CreateNew=1, Create = 2, Open = 3, Truncate = 5 } -all enums inherit from System.Enum, which inherits from System.ValueType -Same rules apply to Struct apply to Enum

Stack Collection:

-Each Element is added to the top -Each element we remove is removed from the top -This is LIFO collection-the stack is last(element)-in-first-out -stack is a generic type-we must specify its stored element type Stack example: Stack<int> stack = new Stack<int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); iterate through stack in foreach like a list<> stack.Pop() stack.Peek() stack.Count() stack.Contains("thing")

Const

-use the const keyword to declare a constant field or a constant local -CANNOT BE MODIFIED AFTER INITIAL ASSIGNMENT const int x = 0; public const double gravitationalConstant = 6.673e-11; private const string productName = "Visual C#"; -different from readonly keyword because const can only be initialize at the declaration of the field; readonly field can be initialized either at the declaration or in a constructor

What are Access Modifiers?

-described as the scope of accessibility of an object and its members(methods) -Private:The scope of accessibility is limited to inside the classes or struct in which they are declared;Private members cannot be accessed outside the class ;least permissive access level -Protected internal:Same access levels of BOTH protected and internal;it can be access from anywhere in the same ASSEMBLY and in the same CLASS;, also the classes inherited from the same clas -Internal:The internal access modifiers provide access to classes and members "within" the program that contain the same assembly level but not from another assembly -Protected The scope of accessibility is limited to within the class or struct and the class derived(inherited) from this class -Public: can be accessed from anywhere,means there is no restriction on accessibility;type or member can be accessed by any other code in the same assembly or another assembly that references it

DAFUQ are Properties???

-enable a class to expose a public way of getting and setting values, while hiding implementation or verification code -get property accessor is used to return the property value set prop accessor is used to assign a new value -value kw is used to define the value being assigned by the set accessor -props can be read-write(get+set),readonly(get),write-only(set) -properties with no custom accessor code are called auto-implemented propertied(simple properties)

What are Constructor?

-enable programmer to set default values, limit instantiation, and write code that is flexible and easy to read -If you dont provide a constructor for your class, C# creates one for you by default Example: public class Person { private string last; private string first; public Person(string lastName, string firstName) { last = lastName; first = firstName; } // Remaining implementation of Person class. }

Disposable Patterns

-if my class has disposable methods, then class needs to be disposable -The .NET Framework provides the System.IDisposable interface that should be implemented to provide the developer a manual way to release unmanaged resources as soon as they are not needded. -It also provides the GC.SuppresFinalize method that can tell the GC that an object was manually disposed of and does not need to be finalized anymore, in which case the objects memory can be reclaimed earlier. -Types that implement the IDisposable interfface are referred to as DISPOSABLE TYPES -DISPOSABLE PATTERN IS intended to standardize the usage and implementation of finalizers and the IDisposable interface -DO implement the Basic Disposable Pattern and provide a finalizer on types holding resources that need to be freed explicitly and that do not have finalizers -Pattern should be implemented on types storing unmanaged memory buffers.

string type

-immutable

Inheritance(official C# flashcard)

-one of the fundamental attributes of object-oriented programming -allows you to define a child class that reuses(inherits), extends, or modifies the behavior of a parent class -base-class:class whose members are inherited -derived class: class who inherits members of base class -C# only allows single-inheritance, but there can be an infinite chain of base to derived classes Following members of a class cant be inherited -static cosntructors(initilialize static data of class) -Instance constructors(which we call to create new instance of class.Each class must define its own constructors) -Finalizers(are called by the runtimes garbage collector to destroy instances of clases) INHERITANCE IS AFFECTEED BY ACCESS MODIFIERS: public, private, internal, protected, protected internal

Git

-online repo for a single collection of assembly where we can see your code -keeps track of your version <><><Tips<><><><><> Rename a file: mv <filename> new <newFileName>

What are Auto-Implemented Properties?

-properties with no custom accessor code are called auto-implemented propertied(simple properties)

Singleton Patterns/DESIGN

-purpose is: -to preserve global state of a type -to share common data across application -to reduce overhead of instantiating a heavy object again and again -suitable for facades and Service proxies -To cache objects in-memory and reuse them throughout the app -Example_Scenarios for Using Singleton: -Service Proxies: in an application invoking a service, aka API, is an extensive operation. By having a service proxy as a Singleton this overhead can be reduced -Facade: DB connections are another example where Singleton can be used to produce better performance and synchronization -Logs:I/O is a heavier operation, by having a single instance of a logger, required information can be written to same file as logs ***ASIDE*** -at any point in time, the application should hold only one instance of the Singleton type. --SO, in order to achieve this, we should mark the constructor of the type as private member; and a method or property should be exposed to outer world to give the Singleton instance ***REFER TO CARET DAY4_TRAININGNOTES*** -A Singleton is a class which (Essentially) only allows one instance of itself to be created- and gives simple, easy access to that one instance(?) -singletons also don't usually have any params

Delegate refer to Day3 training Notes for good example

-the declaration of a delegate type is similar to a method signature;it has a return value and any number of paramters of any type -A delegate is a reference type that can be used to "ENCAPSULATE A NAMED" or an ANONYMOUS method []-it is a type that represents references to methods with a particular parameter list and return type []-when you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type []-you can invoke(or call) the method through the delegate instance []-DELEGATES ARE USED TO PASS METHODS AS ARGUMENTS TO OTHER METHODS; []-Event handlers are nothing more than METHODS THAT ARE INVOKED THROUGH DELEGATES -You create a custom method, and a class such as a windows control can call your method when a certain event(action) occurs []-This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a reference to a method that compares two objects could be passed as an argument to a sort algorithm. Because the comparison code is in a separate procedure, the sort algorithm can be written in a more general way. <><><><><><<><>>><><>><><<> -can be instantiated by associating it either with a named or anonymous method -delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters -for use with anonymous methods, the delegate and the code to be associated with it are declared together

What are namespaces useful for?

-they are what allow you to distinguish your class(es) from others

Downcasting/Upcasting

-upcasting converts an object of a specialized type to a more general type -downcasting converts an object from a general type to a more specialized type

static modifier

-use the static modifier to declare a static member,which belongs to the Type Itself rather than to a specific object. -the static modifier can be used with classes, fields, methods, properties, events, and consrtuctors, but not with finalizers, indexers, or types other than classes A static member/class must have static classes/members in turn a const(tant) or type declaration is implicitly a static member -A static member cannot be referenced through an instance. Instead, it is referenced through the type name: class= MyBaseC; struct = MyStruct static field = int x=100 -to refer to the static member x, us the fully qualified name,: MyBaseC.MyStruct.x -there is only one copy of each static field cant use this to reference static methods or property accessors So, it can be modified, but once you modify it, all references to it are changed as well -MAIN USES FOR STATIC MODIFIER: string of constants your app needs(ton of urls or names)

what is the purpose of var?

-var is used to declare variables -Only use var when type is generally obvious to the reader -var is a way to ask compiler to "infer" the type for you var name = 56;//returns string or int var array = new String[4]; -var works with only one type of Array

var and arrays

-var only works with the simple, built-in array; \var array = new String[or int][4];

Unit Testing /TDD

-way of testing through granular approach -called such because you break down the functionality of your program into discrete testable behaviors that you can test as individual "units" -the more integral part unit testing plays in your code, the more effective it is -as soon as you write a block of code, create unit tests that verify the behavior in response to standard, boundary, and incorrect cases of input data "TDD-TEST DRIVEN DEVELOPMENT" -with test driven development, you create the unit tests before you write the code, so you use the unit tests as both design documentation and functional specs <>><><><><<><><<<>< AAA Pattern: -The aaa(Arrange,Act,Assert) pattern is a common way of writing unit tests for a method under test - the Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test -The Act setion invokes the method under test with the arranged params -The Assert section verifies that the action of the method under test behaves as expected ><><><><><><><><><>< so, for unit testing, create regular class and give it UT attributes and run through test explorer <><><><><>>><><><><> -test method must be decorated with [TestMethod] attribute -method must return void -method cannot have params [TestFixure]-attribute denotes a class that contains unit tests(so put it over a class) [Test]-attribute indicates a method is a test method [Fact]\attribute that is applied to a method to indicate that it is a fact that should be run by the test runner [Theory]: found in xUnit -looks for [inline data] -copies inline data straight into params [MemberData]:expects an object array -gets it from array or method *yield*:takes multiple returned values and stacks them in an enumerable -gewd for when we want to return a collection from a method **ADD MORE ATTRIBUTES,STUPID***

Exampl of While/Do While

-while(trueorfalse) { trueorfalse=false; } System.Console.WriteLine("Because of while loop, trueorfalse now equals = "+trueorfalse); -do { trueorfalse=true; System.Console.WriteLine("\nBecause of Do/While loop, trueorfalse now equals= "+trueorfalse); }while(!trueorfalse);

Dont use foreach to delete items in an array

...

MSIL,CLR - C# code is compiled via MSIL(assembly)

.NET Framework, it[source code] gets compiled into Microsoft Intermediate Language. This MSIL code is then interpreted by the Common Language Runtime, or CLR, which converts it into machine code during execution and feeds it to your computer

ASYNC/AWAIT/TASKS Refer to Caret examples: Day4_TRAININGNOTES

Aynchronous Programming <><>><><><><><><><> -Task Parallel Library(TPL) -task,async,await -theres times when your complex program is sitting there waiting for information(file,web) -Asynchronous programming is how we allow servers and programs to make other actions take place while waiting for others to resolve Synonchronous xample: AccessInternet(url,data =>Process(data)); OUR WAY:Asynchronous data = await AccessInternetAsync(url); data2 = await => Process(data); return true <><><>><><><><><<><><> -Async and Await keywords in C# are the heart of async programming -allows us to use resources in the .net framework .net core or Windows runtime to create an async method -async methods are those defined by using async kw <><><><><><><<><><>< *TASKS* -an async method typically returns a Task or a Task<TResult> ~Task<TResult> as return type if method contains a return statement that specifies an operant of type TResult ~Task as return if method has no return statement or has a return statement that doesnt return an operand -inside an async method, an await operator is applied to a task that returns from a call to another async method Task<Result> async Task<int> TaskofResult_MethodAsync(){ int hrs; return hrs ~consuming ^Method with a Task<int> type~ Task<int> returnedTaskResult = TaskOfResult_MethodAsync(); int intResult = await returnedTaskResult; } //in single statement: int intResult = await TaskOfTResult_MethodAsync(); -Task- async Task Task_MethodAsync(){ } Task returnedTask =Task_MethodAsync(); await returnedTask; -or- await Task_MethodAsync(); <><><><><><><<><><>< An async method cant declare in, ref,or out params, but the method can call methods that have such params. <><><><><><><<><><>< By COnvention, you append "Async" to the names of methods that have an aync modifier -but u can ignore the convention where an even, base class, or interface contract suggests a different name <><><><><><><<><><>< *"AREAS THAT BENEFIT FROM ASYNCHRONY"* *Web access* -.NET types with async methods: HttpClient -Windows Runtime types with async methods: SyndicatonClient *Working With Files* -.NET types with async methods: StreamWriter,SreamReader,XmlReader -Windows Runtime types with async methods: StorageFile *Working With Images* -Windows Runtime types with async methods: MediaCapture,BitmapEncoder,BitmapDecoder *WCF programming* -.NET types with async methods: Synchronous and Asynchronous Operations

Checked/UnChecked

C# statements can execute in either checked or unchecked context. -in a checked context; arithmetic overflow raises an exception -in an unchecked context, arithmetic overflow is ignored and the result is truncated by disregarding any high-order bits that dont fit in the destination type

ABSTRACT METHODS/CLASSES

CLASSES -classes can be declared as abstract by using the kw "abstract" before the class def: public abstract class A { //class members here } -an abstract class cannot be instantiated -purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share -Abstract classes may also define abstract "methods";this is accomplished by adding the kw before the return type of the method METHODS -(usually)have no implementation, so the method'd definition is followed by a semicolon; instead of a normal method block ABSTRACT -derived classes of the abstract class must implement all abstract methods -when an abstract class inherits a "VIRTUAL" method from a base class, the abstract class can override the virtual method with an abstract method Example: abstract class Test { public int _a; public abstract void A(); } class Example1 : Test { public override void A() { cw => "Example print"; base._a++; } } *Within main method*: Test test1 = new Example1(); test1.A();

Class OR Member?

Class and Member: static abstract partial Member only: const readonly sealed virtual override new

Example of using built-in methods

DateTime GetCurrentTime() { return DateTime.Now; } System.Console.WriteLine("\n"+GetCurrentTime());

What are try, catch, and finally

TRY 1-The try block contains a set of statements where an exception can occur. 2-A try block is always followed by a catch block, which handles the exception that occurs in the associated try block 3-Try block must be followed by catch blocks or finally blocks or both While writing a program, if you think that certain statements in a program can throw an exception, enclose them in a try block and handle that exception CATCH 1-a catch block is where you handle the exceptions, this block must follow the try block 2-A single try block can have several catch blocks associated with it 3-You can catch different exceptions in different catch blocks 4-When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. Example: an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes FINALLY 1-Finally block executes whether an exception occurs or not 2-You should place those statements in finally blocks that must execute whether exception occurs or not 3-Order is: Try-Catch-Finally example class Example { public static void main(String args[]) { try{ int num=121/0; System.out.println(num); } catch(ArithmeticException e){ System.out.println("Number should not be divided by zero"); } finally{ System.out.println("This is finally block"); } System.out.println("Out of try-catch-finally"); }

Compiler

Takes source code of some kind and converts it to machine code

CIL

The new name for Microsoft Intermediate language -the lowest-level human-readable programming language defined by the Common language Infrastructure specification ; is used by the .NET framework, .NET Core, and Mono -CLI-targeting language compile to CLI, and CLI is assembled into an object code that has a byte-code style format -CIL is an object-oriented assembly language, and is entirely STACK-BASED

Show Handler(Event Handler(?))

The show handler takes a string and returns nothing

What are generics?

public class MyGenericArray<T> {//can be declared as string or int MyGenericArray<int> = new MyGenericArray<int>(1)//outputs 1 MyGenericArray<string = new myGenericArray<string>(1)//outputs "1" generic types act as placeholders until the time of declaration FOR C############# -generic types are those that are declared as PLACEHOLDERS until client code provides its own when it creates an instance of the type FOR JAVA############ 1-a facility of generic programming that was added to the Java programming language within version J2SE 5.0 2-There were designed to extend Java's type system to allow 'a type or method to operate on objects of various types while providing compile-type safety 3-The Java collections framework supports generics to specify the type of objects stored in a collection instance Generic Classes: 4-a class is generic if it declares one or more type variables; these type variables are known as the type parameters of the class; a generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section Generic Interfaces: 5-An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface; all parameterized types share the same interface at runtime Generic Methods: 6-A method is generic if it declares one or more type variables; the form of the formal type parameter list is identical to a type parameter list of a class or interface Generic Constructors: 7-A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor 8-Generic methods and generic classes ENABLE PROGRAMMERS TO SPECIFY, WITH A SINGLE METHOD DECLARATIN, A SET OF RELATED METHODS, OR WITH A SINGLE CLASS DECLARATION, A SET OF RELATED TYPES, RESPECTIVELY 9-GENERICS ALSO PROVIDE COMPILE-TIME TYPE SAFETY THAT ALLOWS PROGRAMMERS TO CATCH INVALID TYPES AT COMPILE TIME 10-All generic method declarations have a type parameter section delimited by angle brackets(< >) that precedes the method's return type Examples of generics: List '<String>' v= new ArrayList <String>=the generic

method types:

public string GetName(int ID);... in methods, the keyword after public declares what type will be returned, and the <int> kw is the type being received; the params; no other types are allowed to be received or returned

CLR

runtime environment provided by the .NET Framework. -runs the code and provides services that make development much easier processes run during the CLR: -JIT: just-in-time compiler, on run time -BCL: Base Class Library; all the basic stuff that the framework needs -CTS: common type system; a standard that specifies how type definitions and specific values of types are represented in computer memory -VES: Virtual Execution System; the final run time for our code. <>><><><><CLR Advantages<><><><><><>< we have interoperability between language portability across architecture/OS <--core

Modifier Definitions:

sealed-specifies that a class CANNOT BE INHERITED virtual-Declares a method or an accessor whose implementation can be changed by an overriding member in a derived class override-Provides a new implementation of a virtual member inherited from a base class new-explicitly hides a member inherited from a base class partial-defines partial classes, structs and methods throughout the same assembly -partial type definitions allow for the definition of a class,struct, or interface to be split into multiple files(helpful when working on large files)

Abstraction Tips

separation between needed func and implementation details control: -loose coupling -tight couple

Example of Manipulating User Input

string userInput = Console.ReadLine(); System.Console.WriteLine("\nHi, "+userInput+"!!!!\nHow've you been??!?\n");

Example of Switch Statement

switch(integer) { case 0: Console.WriteLine(); break; case 1: Console.WriteLine(); break; case 2: Console.WriteLine("This switch statement works"); break; default: Console.WriteLine("none of the cases matched"); break; }


Conjuntos de estudio relacionados

HESI PN Obstetrics/Maternity Practice Exam

View Set

Artificial Intelligence: A Modern Approach Chapter 3: Solving Problems By Searching

View Set

Ch 27: Nursing Care of the child Born with a Physical or Developmental Challenge

View Set

Epidemiology (7) - Observational Studies

View Set

Real Estate Practice Exam - Property Condition and Disclosure

View Set