Konstantinos pantos Software solutions architect Techaholics C# Crash Course Konstantinos pantos Software solutions architect Techaholics
Agenda Day 1 - C# fundamentals An Introduction to C# Classes and Objects C# - Types C# - Events, Properties, and Methods C# - Flow Control and Exceptions C# and the CLR C# and Generics Default and Named Parameters in C# 4.0
Agenda Day 2 - Introduction to Visual Studio 2012 Getting Started Projects and Solutions Files and Folders Finding Your Way Around Visual Studio Finding Your Way Around Your Code Advanced Finding Your Way Around Your Code Let Visual Studio Help you
Types C# is strongly typed One way to define a type is through a class Every object you work with has a specific Type 1000s of Types are built into the .net framework Code you want to execute must live inside a Type You can place the code inside a method We’ll explore all the things you can put in a Type later…
Primitive Types Name Description Int(32) or int 32bit integer Int(64) or long 64bit integer Boolean or bool True or False Float or float Single precision floating point Double or double Double precision floating point Decimal or decimal Fixed precision (Financial) DateTime An instance in time (to 100ns) String or string Text as Unicode characters
Namespaces Namespace organizes types Fully qualified type names Avoid type name collisions Can define namespace in one or more places Fully qualified type names Includes the assembly name Includes the namespace Includes the type name Using directive Brings other namespaces into scope No need to namespace qualify a Type
Variables Variables hold a value Variables always have a Type Must assign a value before you can use a variable C# compiler will make sure types are compatible during assignment.
Statements & Expressions A statement is an instruction A method is a series of statements Statements end with semicolons Statements are executed in the order they appear Expressions are statements that produce a value Typically involve an operator Can assign the expression value to a new variable or test it TakeOrder(); PackageOrder(); ShipOrder(); int x = 2; int y = 5; int result = x + y;
Operators Specify an operation to perform on one or more variables Mathematical operators (+, -, *, /) Relational operators (<, >, <=, >=) Equality operators (==, !=) Conditional operators(&&, ||) Assignment operators (=, +=, -=, *=, /=)
References Allow you to use types in another assembly Object browser is one way to examine types Reference other assemblies in the FCL Reference 3rd party assemblies Reference other assemblies in solution
An introduction to C#
Overview What is .net What is FCL What is CLR Building “Hello World” Basic expressions and operators Compilers and command line tools Creating projects with Visual Studio
.NET A software framework http://msdn.Microsoft.com/en-us/netframework/default.aspx Your Application CLR Common Language Runtime FCL Framework Class Library
Common Language Runtime CLR The CLR manages your application when it runs Memory management Security Operating system and hardware independence (abstraction) Language Independence CLR Common Language Runtime
Framework Class Library FCL Framework class library A library of functionality to build applications FCL Framework Class Library
What is C# A standardized language to create .net components Standardized by ECMA Create applications, services, and re-usable libraries Syntax is similar to java and C++ public static void Main(string[] args) { if (DateTime.Now.DayOfWeek == DayOfWeek.Monday) { Console.WriteLine("Another case of the Mondays!"); }
Demo – Hello world
CSC.exe The C# command line compiler Transforms C# code into Microsoft Intermediate language Produces an assembly (.dll, .exe)
Demo Visual Studio “Hello world”
Visual Studio An integrated development environment (IDE) Edit C# (and other) files Runs the C# Compiler Debugging Testing
Solution Explorer Will contain at least one project Contains one or more source code files Each project produces an assembly Projects organized under a solution Manage multiple applications or libraries
Summary C# is one of the many languages for .net Syntax similar to C++ and java Strongly typed Statements and expressions Operators References
Classes and Objects
Agenda Classes vs Objects Constructors Inheritance Access modifiers Abstract classes Static classes Sealed classes Partial classes
Classes are to Objects as… Classes define types State Behavior Access Objects are instances of a type You can create multiple instances Each instance holds different state Each instance has the same behavior
Demo wpf application
Constructors Special methods to create objects Set default values Multiple constructors allowed Overloaded methods must take different arguments class Employee { public Employee() { Name = "<Empty>"; Salaried = false; } public bool Salaried { get; set; } public string Name { get; set; } }
Reference Types Classes create reference types Objects are stored on the “heap” Variables reference the object instance Heap Employee Employee worker = new Employee(); worker.Name = "Kostas"; Employee Name = “Kostas” Employee
Object Oriented programming C# is an OO language Inheritance Encapsulation Polymorphism
Inheritance Create classes to extend other classes Classes inherit from System.Object by default Gain all the state and behavior of the base class
Demo Circles & Squares
Access modifiers Keywords that declare accessibility of a type or a member Keyword Applicable to Meaning public class, member No restrictions protected member Access limited to class and derived classes internal Access limited to the current assembly protected internal Access limited to current assembly and derived types private Access limited to the class
Abstract The abstract keyword Abstract class can not be instantiated Can apply to a class Can also apply to members (methods, properties, indexers, events) Abstract class can not be instantiated Abstract classes are designed as base classes Must implement abstract members to make a concrete class public abstract class Animal { public abstract void PerformTrick(); } public class Dog : Animal public override void PerformTrick() { }
Virtual The virtual keyword creates a virtual member Can override the member in the derived class Members are not virtual by default Virtual members dispatch on runtime type public class Animal { public virtual void PerformTrick() { } } public class Dog : Animal public override void PerformTrick() //Perform the animal trick base.PerformTrick(); //then perform the dog trick
Static Static members are members of the type Cannot invoke the member through the object instance Static classes can only have static members Cannot instantiate a static class public static void Main(string[] args) { Console.WriteLine("Hello world"); }
Sealed Sealed classes cannot be inherited Prevent extensibility or misuse Some framework classes are sealed for performance and security reasons
Partial classes Partial classes frequently generated by VS designer Partial class definitions can span multiple files But only in the same project Partial method definitions are extensibility points Optimized away if no implementation provided public partial class Animal { public string Name { get; set; } partial void OnNameChanged(); } public partial class Animal { partial void OnNameChanged() { //implementation }
Summary C# gives you everything you need for oop Encapsulation Inheritance Polymorphism Additional features for performance, convenience, extensibility Static classes Sealed classes Partial classes
C# Types and Assemblies
Agenda Overview Enumerations Structs Interfaces Arrays Assemblies Assembly references
Reference Types Variables store a reference to an object Multiple variables can point to the same object Single variable can point to multiple objects over it’s lifetime Objects allocated on the heap by new operator
Value Types Variables hold the value No pointer or references No object allocated on the heap – lightweight Should be immutable Many built – in primitives are value types Int32, DateTime, Double
Creating Value Types Struct definistions create value types Cannot inherit from a struct (implicitly sealed) Rule of thumb: should be less than 16 Bytes public struct Complex { public int Real; public int Imaginary; }
Demo – Testing reference types
Method parameters Parameters pass by value Parameter keywords Reference types pass a copy of the reference Value types pass a copy of the value Changes to the value don’t propagate to the caller Parameter keywords Ref and out keywords allow passing by reference Ref parameters requires initialized variable public bool Work(ref string text, out int age) { return Int32.TryParse(text, out age); }
Demo – Parameters
The magical String type Strings are reference types But behave like value types Immutable Checking for equality performs a string comparison
Boxing and Unboxing Boxing converts a value type to an object Copies a value into allocated memory on the heap Can lead to performance and memory consumption problems Unboxing converts an object into a value type
Enumerations An enum creates a value type A set of named constants Underlying data type is int by default public enum PayrollType { Contractor = 1, Salaried, Executive, Hourly } PayrollType role = PayrollType.Contractor; if (role == PayrollType.Contractor) { //... }
What makes a value type and a reference type Struct Enum Reference Type class interface delegate array
Interfaces An interface defines a group of related methods, properties and events No implementation defined in interface (very abstract) All members are public Classes and structs can inherit from an interface and provide an implementation Classes and structs can inherit from multiple interfaces interface IMessageLogger { void LogMessage(string message); } class FileSystemLogger : IMessageLogger { public void LogMessage(string message) // ... }
Arrays Simple data structure for managing a collection of variables Everything inside has the same type Always 0 indexed Always derive from abstract base type Array Single dimensional, multi dimensional, and jagged
Demo - Arrays
Assemblies Fundamental building blocks Global assembly cache Implemented as .exe and .dll files Contain metadata about version and all types inside Global assembly cache A central location to store assemblies to a machine Assembly in the gac requires a strong name
Summary Every type is a value type or a reference type Use struct to create a value type Use class to create a reference type Arrays and strings are reference types Strings behave like a value type
Methods properties and events
Methods Methods define behavior Every methods has a return type Void if not value returned Every method has zero or more parameters Use params keyword to accept a variable number of parameters Every method has a signature Name of method + parameters (type and modifiers are significant)
Methods - Review Instance methods versus static methods Instance methods invoked via object, static methods invoked via type Abstract methods Provide no implementation, implicitly virtual Virtual methods Can override in a derived class Partial methods Part of a partial class Extension Methods Described in the Linq session
Method overloading Define multiple methods with the same name in a single class Methods require a unique signature Compiler finds and invokes the best match
Fields Fields are variables of a class Read – only fields Static fields and instance fields Read – only fields Can only assign values in the declaration or in a constructor
Properties Like fields, but do not denote a storage location Every property defines a get and/or a set accessor Often used to expose and control fields Access level for get and set are independent Automatically implemented properties use a hidden field Only accessible via property
Events Allows a class to send notifications to other classes or objects Publisher raises the event One or more subscribers process the event
Delegates A delegate is a type that references methods Similar to a function pointer, but type safe Can invoke methods via a delegate Ideal for callback methods and events
Subscribing to events Use += and -= to attach and detach event handlers Can attached named or anonymous methods
Publishing Events Create custom event arguments (or use built in type) Always derive from the base EventArgs class Define a delegate (or use a built-in delegate) Define an event in your class Raise the event the appropriate time
Indexers Enables indexing of an object (like an array)
Operator Overloading You can overload most uanary and binary operators + - * / ++ -- == < > Overload using static methods Caution – use the principle of least surprise
Conversion Operators Convert an object from one type to the other Implicit or explicit conversion operators Explicit operators require a cast Compiler will automatically find implicit operators
Constructors Instance constructors and static constructors Can overload instance constructors No return type Not inherited Use this keyword or base keyword to pass control to another ctor Variable initializers Easy syntax to create variable and initialize properties
Destructor Used to cleanup an object instance Cannot overload a class destructor Cannot explicitly invoke a destructor Use destructors to release unmanged resources You should always implement IDisposable
Summary Members are used to craft an abstraction Fields and properties for state Methods for behavior Events for notification Overload operators with caution
Control Flow
Overview Branching Iterating Jumping Exceptions
Branching
Switching Restricted to integers, characters, strings and enums No fall through like in C++ Case labels are constants Default label is optional
Iterations
Iterating with foreach Iterates a collection of items Uses the collection’s GetEnumerator method
Jumping break continue goto return throw
Returning and Yielding You can use return in a void method You can use yield to build an Ienumerable
Throw Use throw to raise an exception Exceptions provide type safe and structured error handling in .Net Runtime unwinds the stack until it finds a handler Exception may terminate the application
Built – in exceptions Dozens of exceptions already defined in the FCL Derive from System.Exception Type Description System.DevideByZeroException System.OutOfRangeException System.InvalidCastException System.NullReferenceException System.StackOverflowException System.TypeInitializationException
Handling Exceptions Handle exceptions using a try block Runtime will search for the closest matching catch statement
Finally Finally clause adds finalization code Execute even when control jumps out of scope
Custom Exceptions Derive from a common base exception Use exception suffix on the class name Make the exception serializable
Summary Flow control statements fall into three categories Branching Looping Jumping Exceptions are the error handling mechanism in .net Throw exceptions built-in or custom Catch exceptions
.net and CLR
agenda JIT compilation and garbage collection Threads Reflection and Metadata Processor architecture Interoperability
Garbage collection Garbage collector cleans up unused memory Visits global and local variables to determine what is in use
Threads System.Threading System.Threading.Tasks Low level API for starting, stopping and joining threads System.Threading.Tasks High level API for concurrent and asynchronous programming
Demo - Threading
Reflection CLR provides an API for self examination System.Type is the starting point for reflection
Metadata
Invoking Methods and Properties
Creating Objects Activator class provides static methods to instantiate types
C# on the Metal
COM Interop C# can consume com components C# code can package it self as a COM Component
Pinvoke interop Platform Invoke Can call into Windows APIs and unmanaged code
Summary C# - tightly integrated with CLR Metadata drives many features Can still interop with COM Can still interop with native code Metadata drives many features Garbage collection Reflection
Generics
agenda What are generics Generic classes Generic constraints Generic methods
Why Generics
Solution
Generics Generics types allow code reuse with type safety Class defers specification of a type until instantiated by client Internal algorithms remain the same, only the type changes
Generic Collections System.Collections.Generic HashSet<T> List<T> Queue<T> Stack<T> Dictionary<TKey, TValue> Benefits over System.Collections Type safety Performance (no boxing for value types)
Generic Parameters Use the type parameter as a placeholder Client must specify the type parameter Type parameter name commonly starts with T
Generic Constraints One or more restrictions on the type parameter Force type to be a struct or class For type to have a public default constructor Force type to implement interface or derive from base class
Generic Methods A method requiring a type parameter Static or instance method Can specify constraints Type parameter part of the method signature
Summary Summary Generics create type safe abstractions Classes, structs, interfaces, methods, delegates Apply constraints as required Allows for more specific algorithms
Thank you