Presentation is loading. Please wait.

Presentation is loading. Please wait.

Konstantinos pantos Software solutions architect Techaholics

Similar presentations


Presentation on theme: "Konstantinos pantos Software solutions architect Techaholics"— Presentation transcript:

1 Konstantinos pantos Software solutions architect Techaholics
C# Crash Course Konstantinos pantos Software solutions architect Techaholics

2 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

3 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

4 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…

5 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

6 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

7 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.

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

9 Operators Specify an operation to perform on one or more variables
Mathematical operators (+, -, *, /) Relational operators (<, >, <=, >=) Equality operators (==, !=) Conditional operators(&&, ||) Assignment operators (=, +=, -=, *=, /=)

10 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

11 An introduction to C#

12 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

13 .NET A software framework
Your Application CLR Common Language Runtime FCL Framework Class Library

14 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

15 Framework Class Library
FCL Framework class library A library of functionality to build applications FCL Framework Class Library

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

17 Demo – Hello world

18 CSC.exe The C# command line compiler
Transforms C# code into Microsoft Intermediate language Produces an assembly (.dll, .exe)

19 Demo Visual Studio “Hello world”

20 Visual Studio An integrated development environment (IDE)
Edit C# (and other) files Runs the C# Compiler Debugging Testing

21 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

22 Summary C# is one of the many languages for .net
Syntax similar to C++ and java Strongly typed Statements and expressions Operators References

23 Classes and Objects

24 Agenda Classes vs Objects Constructors Inheritance Access modifiers
Abstract classes Static classes Sealed classes Partial classes

25 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

26 Demo wpf application

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

28 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

29 Object Oriented programming
C# is an OO language Inheritance Encapsulation Polymorphism

30 Inheritance Create classes to extend other classes
Classes inherit from System.Object by default Gain all the state and behavior of the base class

31 Demo Circles & Squares

32 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

33 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()    {           }

34 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

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

36 Sealed Sealed classes cannot be inherited
Prevent extensibility or misuse Some framework classes are sealed for performance and security reasons

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

38 Summary C# gives you everything you need for oop
Encapsulation Inheritance Polymorphism Additional features for performance, convenience, extensibility Static classes Sealed classes Partial classes

39 C# Types and Assemblies

40 Agenda Overview Enumerations Structs Interfaces Arrays Assemblies
Assembly references

41 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

42 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

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

44 Demo – Testing reference types

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

46 Demo – Parameters

47 The magical String type
Strings are reference types But behave like value types Immutable Checking for equality performs a string comparison

48 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

49 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) { //...              }

50 What makes a value type and a reference type
Struct Enum Reference Type class interface delegate array

51 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) // ...          }

52 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

53 Demo - Arrays

54 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

55 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

56 Methods properties and events

57 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)

58 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

59 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

60 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

61 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

62 Events Allows a class to send notifications to other classes or objects Publisher raises the event One or more subscribers process the event

63 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

64 Subscribing to events Use += and -= to attach and detach event handlers Can attached named or anonymous methods

65 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

66 Indexers Enables indexing of an object (like an array)

67 Operator Overloading You can overload most uanary and binary operators
+ - * / == < > Overload using static methods Caution – use the principle of least surprise

68 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

69 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

70 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

71 Summary Members are used to craft an abstraction
Fields and properties for state Methods for behavior Events for notification Overload operators with caution

72 Control Flow

73 Overview Branching Iterating Jumping Exceptions

74 Branching

75 Switching Restricted to integers, characters, strings and enums
No fall through like in C++ Case labels are constants Default label is optional

76 Iterations

77 Iterating with foreach
Iterates a collection of items Uses the collection’s GetEnumerator method

78 Jumping break continue goto return throw

79 Returning and Yielding
You can use return in a void method You can use yield to build an Ienumerable

80 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

81 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

82 Handling Exceptions Handle exceptions using a try block
Runtime will search for the closest matching catch statement

83 Finally Finally clause adds finalization code
Execute even when control jumps out of scope

84 Custom Exceptions Derive from a common base exception
Use exception suffix on the class name Make the exception serializable

85 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

86 .net and CLR

87 agenda JIT compilation and garbage collection Threads
Reflection and Metadata Processor architecture Interoperability

88 Garbage collection Garbage collector cleans up unused memory
Visits global and local variables to determine what is in use

89 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

90 Demo - Threading

91 Reflection CLR provides an API for self examination
System.Type is the starting point for reflection

92 Metadata

93 Invoking Methods and Properties

94 Creating Objects Activator class provides static methods to instantiate types

95 C# on the Metal

96 COM Interop C# can consume com components
C# code can package it self as a COM Component

97 Pinvoke interop Platform Invoke
Can call into Windows APIs and unmanaged code

98 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

99 Generics

100 agenda What are generics Generic classes Generic constraints
Generic methods

101 Why Generics

102 Solution

103 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

104 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)

105 Generic Parameters Use the type parameter as a placeholder
Client must specify the type parameter Type parameter name commonly starts with T

106 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

107 Generic Methods A method requiring a type parameter
Static or instance method Can specify constraints Type parameter part of the method signature

108 Summary Summary Generics create type safe abstractions
Classes, structs, interfaces, methods, delegates Apply constraints as required Allows for more specific algorithms

109 Thank you


Download ppt "Konstantinos pantos Software solutions architect Techaholics"

Similar presentations


Ads by Google