SlideShare a Scribd company logo
1 of 56
Download to read offline
C#
       Patric Boscolo
Microsoft Academic Program
C#
A Component-oriented Language for the
     Microsoft® .NET Framework
Objectives
 Introduction to the C# Language
    Syntax
    Concepts
    Technologies
 Overview of C# Tools and the .NET Framework
Contents
 Section 1: C# Overview
 Section 2: Elements of C#
 Section 3: C# Tools
 Section 4: Putting It All Together
 Summary
Section 1: C# Overview
 Component-oriented Systems
 Component Concepts of .NET
 Why C#?
Component-oriented Systems
 COM
   Most successful component model in history
   Only viable commercial component platform
   Enables cross-organization integration and reuse
 However:
   COM shows its age
       DCOM does not function well over the Internet
       More component-based systems, more quot;DLL Hellquot;
       Even with maturing tools, still too difficult to implement
   COM is not truly language agnostic
       Makes some assumptions of binary layout
       Supports quot;least common denominatorquot; type system only
Component Concepts of .NET
 Take the best of COM+
    Interfaces as abstract contracts
    Components implement and expose interfaces
    Dynamic exploration of capabilities and contracts
    Attribute-driven behavior (transactions, pooling, ...)
 Add
    True object-orientation and inheritance
    Native events model
    Cross-language type system and runtime
    Extensibility at every level
Why C# ?
 First component-oriented language
    Builds on COM+ experience
    Native support for
      Namespaces
      Versioning
      Attribute-driven development

 Power of C with ease of Microsoft Visual Basic®
 Minimal learning curve for everybody
 Much cleaner than C++
 More structured than Visual Basic
 More powerful than Java
Section 2: Elements of C#
 Shape and Structure
 Understanding the C# Type System
 Understanding the C# Language
Shape and Structure
 No header files
 C# employs quot;definition at declarationquot; model
    Much like Visual Basic, Pascal, Modula, Java
 Similar to C++ quot;inlinequot; implementation
    Without implication on code generation
 All code and declaration in one place
    Keeps code consistent and maintainable
    Much better to understand for team collaboration
    Declaration accessible through metadata
 Conditional compilation but no macros
Type System
 Builds on common type system of .NET Framework
 Native access to .NET type system
    C# was born out of .NET
 Core concepts:
    Everything is an object
      Everything implicitly inherits from System.Object
    Clear distinction between value and reference types
      By-Value: Simple Types, Enums, Structs
      By-Reference: Interfaces, Classes, Arrays
Simple Types
 Integer Types
    byte, sbyte (8bit), short, ushort (16bit)
    int, uint (32bit), long, ulong (64bit)
 IEEE Floating Point Types
    float (precision of 7 digits)
    double (precision of 15–16 digits)
 Exact Numeric Type
    decimal (28 significant digits)
 Character Types
    char (single character)
    string (rich functionality, by-reference type)
 Boolean Type
    bool (distinct type, not interchangeable with int)
Enums
Named elements used instead of numbering options
Strongly typed, no automatic conversion to int
Better to use quot;Color.Bluequot; than number expression
   More readable, better maintenance
   Still as lightweight as a plain int
Example: enum Color
            {
                 Red,
                 Green,
                 Blue,
                 Yellow
            };
Arrays
 Zero based, type bound
 Built on .NET System.Array class
 Declared with type and shape, but no bounds
    int[] SingleDim;
    int[,] TwoDim;
    int [][] Jagged;

 Created using new with bounds or initializers
    SingleDim = new int[20];
    TwoDim = new int[,]{{1,2,3},{4,5,6}};
    Jagged = new int[1][];
    Jagged[0] = new int[]{1,2,3};
Namespaces
 Every definition must be contained in a namespace
    Avoids name collisions
    Enforces order
    Makes API's easier to comprehend
 Can and should be nested
 Group classes and types by semantics
 Declared with keyword namespace
 Referenced with using
Interfaces
 Declarations of semantics contracts between parties
    Enables component orientation
 Define structure and semantics for specific purposes
 Abstract definitions of methods and properties
 Support (multiple) inheritance
 Example: interface IPersonAge
            {
                int YearOfBirth {get; set;}
                int GetAgeToday();
            }
Classes
                                          public class Person :
Implementation of code and data                            IPersonAge
                                          {
   Represents semantic unit                  private int YOB;

                                              public Person()
Implement interfaces                          {
                                              }
Inherit from single base class                public int YearOfBirth
                                              {
Classes contain:                                 get { return YOB; };
                                                 set { YOB = value; };
   Fields: member variables                   }

                                              public int GetAgeToday()
   Properties: values accessed                {
   through get/set method pairs                  return Today()-
                                                        YearOfBirth
   Methods: functionality for object or       };
   class                                  }

   Specials: events, indexers,
   delegates
Structs
 Groups of data and code
    Similar to classes, however:
      No inheritance allowed
      Always passed by value
    Classes vs. Structs
      Struct    Lightweight data container, value type
      Class     Rich object with references, reference type

 C++ Developers!
    Struct is not a class with everything being public
 Example:      struct Point
               {
                  double X;
                  double Y;
                  void MoveBy(double dX, double dY)
                  { X+=dX; Y+=dY; }
               }
Properties
 Mix between fields and methods
 Use properties for:
    Implementation of read-only members
    (by omitting set)
    Validation on assignment
    Calculated or composed values
    Exposing values on interfaces
 Example:    string Name
             {
                get { return name; }
                set { name = value; }
             }
Indexers
 Consistent way to build containers
 Build on properties idea
 Allow indexed access to contained objects
 Index qualifier may be of any type
 Example:    object this[string index]
             {
               get { return Dict.Item(index); }
               set { Dict.Add(index,value); }
             }
Delegates
 Similar to function pointers found in C and C++
 Strongly typed, no type-cast confusion or errors
 Declaration creates typed method signature:
    delegate void Clicked(Element e, Point p);

 Actual delegate is an instance of this type
    Clicked MyClickHandler
       = new Clicked(obj.OnButtonClick);

 Argument passed to delegate constructor:
    Reference to object instance and method
    Method must have the exact same signature
       void OnButtonClick(Element e, Point p) { ... };
Events
  Language-intrinsic event model
  All management done by C#
  Events are declared using a delegate type
  Declaration creates event source to bind to
     event Clicked OnClicked;

  Event sinks bind to event source with delegates
     Add handler:
         btnAction.OnClicked += MyClickHandler;
     Remove handler:
         btnAction.OnClicked -= MyClickHandler;

  Event source triggers event sinks with single call
     OnClicked(this,PointerLocation);
Attributes
 Similar to attributes known from IDL
 Declarative access to functionality
 Extensible through custom attributes
 Allow code augmentation with:
    Hints for the runtime environment
      [Transaction(TransactionOption.Required)]
      class MyBusinessComponent
                :ServicedComponent { ... }
    Declarative semantics
      [PersonFirstName] String Vorname;
      [PersonFirstName] String PrimarioNome;
Creating Custom Attributes
 Implement class with Attribute base class
 Automatically extend language (!)
 Explore through .NET reflection
    O.GetType().GetCustomAttributes(…);

 Example:
 class PersonFirstNameAttribute : Attribute
 {
       public PersonFirstName()
       {
       }
 }
Statements
 Very C: Flow Control and Loops
   if (<bool expr>) { ... } else { ... };
   switch(<var>) { case <const>: ...; };
   while (<bool expr>) { ... };
   for (<init>;<bool test>;<modify>) { ... };
   do { ... } while (<bool expr>);

 Very not C:
   lock(<object>){ ... };
      Language inherent critical section synchronization
   checked {...}; unchecked { ...};
      Integer overflow protection
Collections Built-in: foreach
 Straightforward support for iterating over collections
    Can be used for arrays and other collections
 Can also be used with any custom class
    Implements IEnumerable with GetEnumerator()
    Returning object implementing IEnumerator
 Example: Point[] Points = GetPoints();
            foreach( Point p in Points )
            {
               MyPen.MoveTo(p.x,p.y);
            }
Operators
 Very C:
    Logical/conditional: && || ^
    Arithmetic:         * / + - % << >>
    Relational:         == != < > >= <=

 Not exactly C:
    For bool: & and | are logical with full evaluation
    For integer: & and | perform binary AND/OR
 Very un-C:
    is        Tests run-time type
    as        Converts a value to a specified type
    typeof Retrieves run-time type
Operator Overloading
 Most operators can be overloaded
    Arithmetic, relational, conditional, and logical
 No overloading for
    Assignment operators
    Special operators (sizeof, new, is, typeof)
 Example: Total operator +(int Amount, Total t)
            {
                t.total += Amount;
            }
Access Protection
 Adopts C++ model
   public     Everyone may call or access
   protected       Only members may access
   private     Only members of exactly this class
 Expands C++ model
   sealed       Can't use as base class
   internal    Public access only within assembly
   protected internal      Protected in assembly
“Pointers, I need pointers!”
 C# supports
    Intrinsic string type
    Rich garbage-collection model
    By-reference parameters using ref
     void increment(ref int value, int by)
    Outbound parameters using out
     bool add(int a, int b, out int c)

 Eliminates vast majority of C++ uses of pointers
 Pointers are available for code marked unsafe
   unsafe void crypt(byte[] arr)
   {
      byte * b = arr;
      ...
   }
Boxing and Unboxing
 By-value types can be quot;boxedquot; and quot;unboxedquot;
 quot;Boxingquot; allows by-value types to travel by-ref
 Based on objectness of all types.
 Think: Throw value in box and reference the box

                       double Value;
42          42
                       // Boxing
                       object BoxedValue = Value;
                       // Unboxing
            42         Value = (double)BoxedValue;

      Boxed:     Unboxed:
     Reference    Copy
Garbage Collection 1/2
   C/C++ applications often leak memory
      Manual memory management
      No clear rules for ownership of objects
   COM fixes this partly through ref-counts
      AddRef/Release calls must be balanced
      SmartPointers don't catch all problems
   Server applications must be leak free
      Must run for months and years
   Solution: automatic memory management
Garbage Collection 2/2
   Developer creates new objects and data arrays
      Everything created/allocated using new keyword
   The .NET runtime tracks all memory usage
   automatically
   GC automatically removes all unused objects
   More efficient memory management
   Ease of use and quot;zero memory leaksquot;
Nondeterministic Destruction
   Garbage Collection downside:
      Destructors called at some random future time
      Finalization code is never synchronous
      Breaks some established design patterns from C++
   Beware: Code should never depend on destructors
   to free external resources.
   Instead: Implement IDisposable with using
      using( File f = new File(quot;c:xyz.xmlquot;) )
      {
           ...
      }
      IDisposable.Dispose() called on object when scope is exited.
Exception Handling
 Very similar to C++ and SEH
 Read like this:
    try running this code ...
    ... if error occurs, catch what I can deal with ...
    ...finally allow me to do some manual cleanup work
 Example:    try
             {
                //... run code
             }
             catch(SomeException e)
             {
                //... handle
             }
             finally
             {
                //...end gracefully
             }
Core Differences from C++
 C# looks a lot like C/C++
 Fixes a lot of common bug sources:
    Stricter type-checking, very unforgiving with type-casts
    No quot;fall-throughquot; in switch
    Boolean expressions are strongly typed
    Better access protection, no cheating through headers
    quot;Mostly no pointersquot;   quot;Mostly no GPFquot;
    Forget hunting memory leaks
Class Version Management
 Real Life:
    Two people at two places write two pieces of software
    A's class builds on B's class
    B implements a method CalcResult
    Next version, A also adds CalcResult
       Q: Does B want CalcResult to be an override of A's ?
       A: Unlikely.

 Solution: Must state intent when using inheritance
    Must specify override to override a method
    Can specify new virtual to never inherit from base
Goodies: XML Comments
Consistent, intrinsic way to create doc from code
Triple-slash quot;///quot; comments are exported
Extract full documentation during compile with /doc
Comes with predefined schema
Example:   ///<summary>
           /// This function serves to calculate the
           /// overall value of the item including all
           /// taxes
           /// </summary>
           /// <remarks>
           /// Tax calculates in CalcTax()
           /// </remarks>
           public decimal GetTotalValue()
           {
           }
Section 3: The Tools
 .NET Framework SDK—all you need to build apps
    C# compiler
    Visual debugger
    Nmake
 Visual Studio.NET—the productivity rocket
    Development environment optimized for C#
    Code wizards and templates
    Smart help
.NET Framework SDK
 C# compiler (plus Visual Basic, C++, and JScript)
    All language features
    Runs from the command line
 Visual Debugger—GuiDebug
    Built on Visual Studio.NET technology
    Full access to runtime metadata
 Tools
    Nmake, security, configuration, IL Disassembler, ...
 Free for everyone
Visual Studio.NET
 Built on the .NET Framework SDK
 Reinvention of the concept of Visual Studio®, now with:
    Multiple-language projects
    One integrated development environment for all
    languages and tasks
    Integrated tools: Visual Modeler, Database Management
    Perfect help integration: Dynamic Help, IntelliSense®
 Highest productivity for all:
    Rapid application development
    Large-scale projects
Section 4: Putting It All Together
 Samples
   The Classic Start: quot;Hello World!quot; in C#
   Exploring C# Features in Duwamish Books
Hello World
namespace Sample
{
  using System;

    public class HelloWorld
    {
        public HelloWorld()
        {
        }

        public static int Main(string[] args)
        {
           Console.WriteLine(quot;Hello World!quot;);
           return 0;
        }
    }
}
Hello World Anatomy
 Contained in its own namespace
 References other namespaces with quot;usingquot;
 Declares a publicly accessible application class
 Entry point is quot;static int Main( ... )quot;
 Writes quot;Hello World!quot; to the system console
    Uses static method WriteLine on System.Console
Summary
C# builds on the .NET Framework component model
New language with familiar structure
   Easy to adopt for developers of C, C++, Java, and
   Visual Basic applications
Fully object oriented
Optimized for the .NET Framework
Questions?
To C# from Visual Basic
   A very brief introduction to the C language
   family syntax for Visual Basic developers
C
Core principles: Be brief. Be expressive.
    Relatively few and short keywords
    Uses symbol ASCII characters instead of words
Core element: quot;{quot; The Block quot;}quot;
    Code groups for structural or flow-control elements

Blocks in Visual Basic        Blocks in C
Sub Xyz()                     void Xyz() {
   'Code                         /*Code*/
End Sub                       }

If MyVal=0 Then               if (MyVal==0) {
   'Code                         /*Code*/
End If                        }
Statements
                   All statements (quot;do that!quot;) are inside blocks
                           Every statement is terminated with a semicolon quot;;quot;
                           White space, line breaks, tabs are not significant
                           May have many statements on one line
                           Statements may be split across lines

                        Statements:                                                     Just as legal: This too:                             #define/**/X
                                                                                                                                          char*d=quot;X0[!4cM,!quot;
                                                                                                                      quot;            4cK`*!4cJc(!4cHg&!4c$jquot;
                                                                                                                                  quot;8f'!&~]9e)!'|:d+!)rAc-!*m*quot;
                                                                                                                  quot;             :d/!4c(b4e0!1r2e2!/t0e4!-y-c6!quot;




                        a = add( 2, 3 );                                                a=
                                                                                                              quot;              +|,c6!)f$b(h*c6!(d'b(i)d5!(b*a'`&cquot;
                                                                                                                           quot;)c5!'b+`&b'c)c4!&b-_$c'd*c3!&a.h'd+quot;
                                                                                                                         quot;d1!%a/g'e+e0!%b-g(d.d/!&c*h'd1d-!(d%g)quot;
                                                                                                                       quot;d4d+!*l,d7d)!,h-d;c'!.b0c>d%!A`Dc$![7)35Equot;
                                                                                                                    quot;!'1cA,,!2kE`*!-s@d(!(k(f//g&!)f.e5'f(!+a+)quot;
                                                                                                                    quot;f%2g*!?f5f,!=f-*e/!<d6e1!9e0'f3!6f)-g5!4d*bquot;
                                                                                                                    quot;+e6!0f%k)d7!+~^'c7!)z/d-+!'n%a0(d5!%c1a+/d4quot;
                                                                                                                    quot;!2)c9e2!9b;e1!8b>e/!                   7cAd-!5fAe+!7fBe(!quot;
                                                                                                                   quot;8hBd&!:iAd$![7S,Q0!1                  bF 7!1b?'_6!1c,8b4quot;
                                                                                                                   quot;!2b*a,*d3!2n4f2!${4               f.             '!%y4e5!&f%quot;




                        q = a – 1;                                                      add
                                                                                                                  quot;d-^-d7!4c+b)d9!4c-a              'd                 :!/i('`&dquot;
                                                                                                                  quot;;!+l'a+d<!)l*b(d=!'            m-                 a &d>!&d'quot;
                                                                                                                quot;`0_&c?!$dAc@!$cBc@!$             b                  <         ^&d$`quot;
                                                                                                                quot;:!$d9_&l++^$!%f3a'             n1                 _              $ !&quot;
                                                                                                               quot;f/c(o/_%!(f+c)q*c              %!                  *              f &d+quot;
                                                                                                               quot;f$s&!-n,d)n(!0i-             c-                  k)               ! 3dquot;
                                                                                                               quot;/b0h*!H`7a,![7*             i]                   5                4     71quot;
                                                                                                              quot;[=ohr&o*t*q*`*d              *v                 *r                   ; 02quot;
                                                                                                              quot;7*~=h./}tcrsth             &t                   :                    r    9bquot;




                        out( q );                                                       (2,3
                                                                                                             quot;].,b-725-.t--//             #r                 [                      <    t8-quot;
                                                                                                             quot;752793? <.~;b              ].t--+r             /                      #     53quot;
                                                                                                             quot;7-r[/9~X .v90              <6/<.v;-52/={                                k   gohquot;
                                                                                                             quot;./}q;     u vto          hr `.i*$engt$                                  $     ,bquot;
                                                                                                             quot;;$/       =t ;v;         6        =`it.`;7=`                            :     ,b-quot;
                                                                                                             quot;725      = / o`.       .d             ;b]`--[/+                     55/        }oquot;
                                                                                                             quot;`.d    :     - ?5      /                    }o`.'              v/i]q           - quot;
                                                                                                             quot;-[;    5 2 =` it                            .                o;53-             . quot;
                                                                                                             quot;v96    <7 /         =o                      :                       d           =oquot;




                        q--;                                                            );q=a
                                                                                                             quot;--/i ]q--           [;                    h.                        /           = quot;
                                                                                                             quot;i]q--[ ;v           9h                    ./                        <           - quot;
                                                                                                             quot;52={cj     u        c&`                   i      t               . o            ; quot;
                                                                                                             quot;?4=o:d=             o--                   / i                    ]q             - quot;
                                                                                                             quot;-[;54={ cj          uc&                   i]q                     -               -quot;
                                                                                                             quot;[;76=i]q[;6         =vsr                u.i                       /               ={quot;
                                                                                                             quot;=),BihY_gha         ,)0                quot;                         ,               o [
                                                                                                              3217];int i,       r,w,f                ,                           b           ,x ,
                                                                                                              p;n(){return       r <X                 X                             X         X X




                        return;                                                         –1;out
                                                                                                              768?d[X(143+       X r++                +                             *d        ) %
                                                                                                               768]:r>2659       ? 59:                (                               x       = d
                                                                                                               [(r++-768)%       X 947              +                          768]           ) ?
                                                                                                               x^(p?6:0):(p =          34           X                        X                X )
                                                                                                               ;}s(){for(x= n          ();          (                      x^                 ( p
                                                                                                              ?6:0))==32;x= n            ()         )       ;return x                         ; }
                                                                                                              void/**/main X             ()         {                      r                 = p
                                                                                                              =0;w=sprintf (X             X         X                  X X                   X o
                                                                                                              ,quot;char*d=quot;); for                      (        f=1;f <                         * d




                                                                                        (q);q—-
                                                                                                              +143;)if(33-( b=d                     [            f++ X                      ] )
                                                                                                              ){if(b<93){if       X(!               p                    )                    o
                                                                                                               [w++]=34;for        X(i              =                  35                     +
                                                                                                                (p?0:1);i<b;         i++            )                  o
                                                                                                                [w++]=s();o[           w++                             ]
                                                                                                                  =p?s():34;}          else                            X
                                                                                                                    {for(i=92;           i<b;                        i
                                                                                                                     ++)o[w++]=           32;}                       }
                                                                                                                           else o         [w++                     ]




                                                                                        ;return;
                                                                                                                             =10;o              [
                                                                                                                                 w]=0           ;
                                                                                                                                                    puts(o);}




quot;This tooquot; Credits: Don Yang, Winner quot;Best Layoutquot; International Obfuscated C Contest http://www.ioccc.org
Declaration Principles
Core declaration principle: quot;What then whoquot;
What: data type or declaration keyword
   Types: int, string, decimal, float
   Keywords: enum, struct, class
Who: user-defined identifier
   Must begin with a letter, may contain numbers, quot;_quot;
   Attention: All identifiers are case sensitive

 Variable declarations:          Structure declaration:
 int MyValue;
 string MyName;                  struct Point {
                                    int x; int y;
 Function declaration:           }
 int MyFunc(string Arg);
Operators
Arithmetic
   binary operators          quot;oprd1 operator oprd2quot;
      add (+), subtract (-), divide (/), multiply (*)
      Modulo (%)       a=b%c; instead of a=b mod c
   unary operators           quot;oprd1 operatorquot;
      increment (++), decrement (--)        i++ instead of i=i+1

Logical
   and (&&), or (||), not(!)
Bitwise
   and (&), or(|), xor (^), not (~)
Relational
   equal (==), not equal (!=), less (<)
   greater (>), less equal (<=), greater equal (>=)
Expressions
Boolean expressions
   Evaluate to true or false
   (2 == 1) is false, (2 > 1) is true

Arithmetic expressions like Visual Basic
   1 + 2 * (6 / 2)

Assignment
   a = 1;      also at declaration time: int a = 0;
   a += 4;      equivalent to a = a + 4;
   a *= 2;      equivalent to a = a * 2;
     works with all binary operators.
Flow Control
 Conditional execution of code blocks:
    if (<expression>) <block> [else <block>];

 Selective execution of code blocks:
    switch(<variable>) {
      case <value>:
             <statements>; break;
    }

                               switch (i)
                               {
  if (i == 0 )                    case 0:
  {                                 Console.Write(quot;Thisquot;);
     Console.Write(quot;Thisquot;);         break;
  }                               case 1:
  else                              Console.Write(quot;Thatquot;);
  {                                 break;
      Console.Write(quot;Thatquot;);      default:
  };                                Console.Write(quot;Elsequot;);
                                    break;
                               }
Loops
Counted loops
    for(<pre>;<while>;<increment>) <block>
    <pre>: Setting precondition quot;i=0quot;
    <while>: Testing continuation condition quot;i<10quot;
    <increment>: Calculating counter state quot;i++quot;
While loops
    while (<expression>) <block>
    do <block> while (<expression>);

 for (i=0; i< 10; i++ )     while ( !MyFile.EOF )
 {                          {
    Console.Write(i);          Console.Write(MyFile.Read());
 }                          }
Other Noteworthy Things ...
The data type quot;voidquot; means quot;no typequot;
     method void func(int a) returns nothing
     Like a quot;Subquot; in Visual Basic
     method int func(void) has no arguments
C has pointers. In C# you do not need them
     Don't worry about them
   Reference and value types are clearly defined
   ref keyword for values by reference
Very few keywords and intrinsic functionality
   quot;Cquot; languages rely heavily on run-time libraries
   Example: Math.Pow(a,b) instead of a^b
Legal Notices
 Unpublished work. © 2001 Microsoft Corporation. All rights
 reserved.
 Microsoft, IntelliSense, JScript, Visual Basic, Visual Studio, and
 Windows are either registered trademarks or trademarks of
 Microsoft Corporation in the United States and/or other
 countries.
 The names of actual companies and products mentioned
 herein may be the trademarks of their respective owners.

More Related Content

What's hot

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Ameen Sha'arawi
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three noskrismishra
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsSubhransu Behera
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented ProgrammingGamindu Udayanga
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphismFALLEE31188
 

What's hot (20)

Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Inheritance
InheritanceInheritance
Inheritance
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
OOP C++
OOP C++OOP C++
OOP C++
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
C++ classes
C++ classesC++ classes
C++ classes
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 

Viewers also liked

Viewers also liked (20)

Novay 8 december 2011
Novay 8 december 2011Novay 8 december 2011
Novay 8 december 2011
 
Novidades do .Net 4.0
Novidades do .Net 4.0Novidades do .Net 4.0
Novidades do .Net 4.0
 
TTA: 6 Word Digital Memoirs
TTA: 6 Word Digital MemoirsTTA: 6 Word Digital Memoirs
TTA: 6 Word Digital Memoirs
 
21st Century Tools for Health Leaders
21st Century Tools for Health Leaders21st Century Tools for Health Leaders
21st Century Tools for Health Leaders
 
Reed
ReedReed
Reed
 
2009
20092009
2009
 
2ª Investidura em Granito
2ª Investidura em Granito2ª Investidura em Granito
2ª Investidura em Granito
 
IPTV Challenges
IPTV ChallengesIPTV Challenges
IPTV Challenges
 
1099 Economy Growth and Challenges
1099 Economy Growth and Challenges1099 Economy Growth and Challenges
1099 Economy Growth and Challenges
 
PIG
PIGPIG
PIG
 
Webtalk 2ª Edição - Aula 6
Webtalk 2ª Edição - Aula 6Webtalk 2ª Edição - Aula 6
Webtalk 2ª Edição - Aula 6
 
Zer da kp aurkezpena
Zer da kp aurkezpenaZer da kp aurkezpena
Zer da kp aurkezpena
 
Open Source
Open SourceOpen Source
Open Source
 
Print Media Today - Breda, NHTV 05102014
Print Media Today - Breda, NHTV 05102014Print Media Today - Breda, NHTV 05102014
Print Media Today - Breda, NHTV 05102014
 
Danae
DanaeDanae
Danae
 
The Moore-Spiegel Oscillator
The Moore-Spiegel OscillatorThe Moore-Spiegel Oscillator
The Moore-Spiegel Oscillator
 
Drupaljam20062011
Drupaljam20062011Drupaljam20062011
Drupaljam20062011
 
HELLVILLE FINAL
HELLVILLE FINALHELLVILLE FINAL
HELLVILLE FINAL
 
Has Anyone Asked a Customer?
Has Anyone Asked a Customer?Has Anyone Asked a Customer?
Has Anyone Asked a Customer?
 
TTF I Spy Nouns
TTF I Spy NounsTTF I Spy Nouns
TTF I Spy Nouns
 

Similar to 1204csharp

Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#singhadarsh
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpvoegtu
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpvoegtu
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharphmanjarawala
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpsinghadarsh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharpMody Farouk
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...NALESVPMEngg
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptAlmamoon
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptmothertheressa
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharpNaved khan
 

Similar to 1204csharp (20)

Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
C#ppt
C#pptC#ppt
C#ppt
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

1204csharp

  • 1. C# Patric Boscolo Microsoft Academic Program
  • 2. C# A Component-oriented Language for the Microsoft® .NET Framework
  • 3. Objectives Introduction to the C# Language Syntax Concepts Technologies Overview of C# Tools and the .NET Framework
  • 4. Contents Section 1: C# Overview Section 2: Elements of C# Section 3: C# Tools Section 4: Putting It All Together Summary
  • 5. Section 1: C# Overview Component-oriented Systems Component Concepts of .NET Why C#?
  • 6. Component-oriented Systems COM Most successful component model in history Only viable commercial component platform Enables cross-organization integration and reuse However: COM shows its age DCOM does not function well over the Internet More component-based systems, more quot;DLL Hellquot; Even with maturing tools, still too difficult to implement COM is not truly language agnostic Makes some assumptions of binary layout Supports quot;least common denominatorquot; type system only
  • 7. Component Concepts of .NET Take the best of COM+ Interfaces as abstract contracts Components implement and expose interfaces Dynamic exploration of capabilities and contracts Attribute-driven behavior (transactions, pooling, ...) Add True object-orientation and inheritance Native events model Cross-language type system and runtime Extensibility at every level
  • 8. Why C# ? First component-oriented language Builds on COM+ experience Native support for Namespaces Versioning Attribute-driven development Power of C with ease of Microsoft Visual Basic® Minimal learning curve for everybody Much cleaner than C++ More structured than Visual Basic More powerful than Java
  • 9. Section 2: Elements of C# Shape and Structure Understanding the C# Type System Understanding the C# Language
  • 10. Shape and Structure No header files C# employs quot;definition at declarationquot; model Much like Visual Basic, Pascal, Modula, Java Similar to C++ quot;inlinequot; implementation Without implication on code generation All code and declaration in one place Keeps code consistent and maintainable Much better to understand for team collaboration Declaration accessible through metadata Conditional compilation but no macros
  • 11. Type System Builds on common type system of .NET Framework Native access to .NET type system C# was born out of .NET Core concepts: Everything is an object Everything implicitly inherits from System.Object Clear distinction between value and reference types By-Value: Simple Types, Enums, Structs By-Reference: Interfaces, Classes, Arrays
  • 12. Simple Types Integer Types byte, sbyte (8bit), short, ushort (16bit) int, uint (32bit), long, ulong (64bit) IEEE Floating Point Types float (precision of 7 digits) double (precision of 15–16 digits) Exact Numeric Type decimal (28 significant digits) Character Types char (single character) string (rich functionality, by-reference type) Boolean Type bool (distinct type, not interchangeable with int)
  • 13. Enums Named elements used instead of numbering options Strongly typed, no automatic conversion to int Better to use quot;Color.Bluequot; than number expression More readable, better maintenance Still as lightweight as a plain int Example: enum Color { Red, Green, Blue, Yellow };
  • 14. Arrays Zero based, type bound Built on .NET System.Array class Declared with type and shape, but no bounds int[] SingleDim; int[,] TwoDim; int [][] Jagged; Created using new with bounds or initializers SingleDim = new int[20]; TwoDim = new int[,]{{1,2,3},{4,5,6}}; Jagged = new int[1][]; Jagged[0] = new int[]{1,2,3};
  • 15. Namespaces Every definition must be contained in a namespace Avoids name collisions Enforces order Makes API's easier to comprehend Can and should be nested Group classes and types by semantics Declared with keyword namespace Referenced with using
  • 16. Interfaces Declarations of semantics contracts between parties Enables component orientation Define structure and semantics for specific purposes Abstract definitions of methods and properties Support (multiple) inheritance Example: interface IPersonAge { int YearOfBirth {get; set;} int GetAgeToday(); }
  • 17. Classes public class Person : Implementation of code and data IPersonAge { Represents semantic unit private int YOB; public Person() Implement interfaces { } Inherit from single base class public int YearOfBirth { Classes contain: get { return YOB; }; set { YOB = value; }; Fields: member variables } public int GetAgeToday() Properties: values accessed { through get/set method pairs return Today()- YearOfBirth Methods: functionality for object or }; class } Specials: events, indexers, delegates
  • 18. Structs Groups of data and code Similar to classes, however: No inheritance allowed Always passed by value Classes vs. Structs Struct Lightweight data container, value type Class Rich object with references, reference type C++ Developers! Struct is not a class with everything being public Example: struct Point { double X; double Y; void MoveBy(double dX, double dY) { X+=dX; Y+=dY; } }
  • 19. Properties Mix between fields and methods Use properties for: Implementation of read-only members (by omitting set) Validation on assignment Calculated or composed values Exposing values on interfaces Example: string Name { get { return name; } set { name = value; } }
  • 20. Indexers Consistent way to build containers Build on properties idea Allow indexed access to contained objects Index qualifier may be of any type Example: object this[string index] { get { return Dict.Item(index); } set { Dict.Add(index,value); } }
  • 21. Delegates Similar to function pointers found in C and C++ Strongly typed, no type-cast confusion or errors Declaration creates typed method signature: delegate void Clicked(Element e, Point p); Actual delegate is an instance of this type Clicked MyClickHandler = new Clicked(obj.OnButtonClick); Argument passed to delegate constructor: Reference to object instance and method Method must have the exact same signature void OnButtonClick(Element e, Point p) { ... };
  • 22. Events Language-intrinsic event model All management done by C# Events are declared using a delegate type Declaration creates event source to bind to event Clicked OnClicked; Event sinks bind to event source with delegates Add handler: btnAction.OnClicked += MyClickHandler; Remove handler: btnAction.OnClicked -= MyClickHandler; Event source triggers event sinks with single call OnClicked(this,PointerLocation);
  • 23. Attributes Similar to attributes known from IDL Declarative access to functionality Extensible through custom attributes Allow code augmentation with: Hints for the runtime environment [Transaction(TransactionOption.Required)] class MyBusinessComponent :ServicedComponent { ... } Declarative semantics [PersonFirstName] String Vorname; [PersonFirstName] String PrimarioNome;
  • 24. Creating Custom Attributes Implement class with Attribute base class Automatically extend language (!) Explore through .NET reflection O.GetType().GetCustomAttributes(…); Example: class PersonFirstNameAttribute : Attribute { public PersonFirstName() { } }
  • 25. Statements Very C: Flow Control and Loops if (<bool expr>) { ... } else { ... }; switch(<var>) { case <const>: ...; }; while (<bool expr>) { ... }; for (<init>;<bool test>;<modify>) { ... }; do { ... } while (<bool expr>); Very not C: lock(<object>){ ... }; Language inherent critical section synchronization checked {...}; unchecked { ...}; Integer overflow protection
  • 26. Collections Built-in: foreach Straightforward support for iterating over collections Can be used for arrays and other collections Can also be used with any custom class Implements IEnumerable with GetEnumerator() Returning object implementing IEnumerator Example: Point[] Points = GetPoints(); foreach( Point p in Points ) { MyPen.MoveTo(p.x,p.y); }
  • 27. Operators Very C: Logical/conditional: && || ^ Arithmetic: * / + - % << >> Relational: == != < > >= <= Not exactly C: For bool: & and | are logical with full evaluation For integer: & and | perform binary AND/OR Very un-C: is Tests run-time type as Converts a value to a specified type typeof Retrieves run-time type
  • 28. Operator Overloading Most operators can be overloaded Arithmetic, relational, conditional, and logical No overloading for Assignment operators Special operators (sizeof, new, is, typeof) Example: Total operator +(int Amount, Total t) { t.total += Amount; }
  • 29. Access Protection Adopts C++ model public Everyone may call or access protected Only members may access private Only members of exactly this class Expands C++ model sealed Can't use as base class internal Public access only within assembly protected internal Protected in assembly
  • 30. “Pointers, I need pointers!” C# supports Intrinsic string type Rich garbage-collection model By-reference parameters using ref void increment(ref int value, int by) Outbound parameters using out bool add(int a, int b, out int c) Eliminates vast majority of C++ uses of pointers Pointers are available for code marked unsafe unsafe void crypt(byte[] arr) { byte * b = arr; ... }
  • 31. Boxing and Unboxing By-value types can be quot;boxedquot; and quot;unboxedquot; quot;Boxingquot; allows by-value types to travel by-ref Based on objectness of all types. Think: Throw value in box and reference the box double Value; 42 42 // Boxing object BoxedValue = Value; // Unboxing 42 Value = (double)BoxedValue; Boxed: Unboxed: Reference Copy
  • 32. Garbage Collection 1/2 C/C++ applications often leak memory Manual memory management No clear rules for ownership of objects COM fixes this partly through ref-counts AddRef/Release calls must be balanced SmartPointers don't catch all problems Server applications must be leak free Must run for months and years Solution: automatic memory management
  • 33. Garbage Collection 2/2 Developer creates new objects and data arrays Everything created/allocated using new keyword The .NET runtime tracks all memory usage automatically GC automatically removes all unused objects More efficient memory management Ease of use and quot;zero memory leaksquot;
  • 34. Nondeterministic Destruction Garbage Collection downside: Destructors called at some random future time Finalization code is never synchronous Breaks some established design patterns from C++ Beware: Code should never depend on destructors to free external resources. Instead: Implement IDisposable with using using( File f = new File(quot;c:xyz.xmlquot;) ) { ... } IDisposable.Dispose() called on object when scope is exited.
  • 35. Exception Handling Very similar to C++ and SEH Read like this: try running this code ... ... if error occurs, catch what I can deal with ... ...finally allow me to do some manual cleanup work Example: try { //... run code } catch(SomeException e) { //... handle } finally { //...end gracefully }
  • 36. Core Differences from C++ C# looks a lot like C/C++ Fixes a lot of common bug sources: Stricter type-checking, very unforgiving with type-casts No quot;fall-throughquot; in switch Boolean expressions are strongly typed Better access protection, no cheating through headers quot;Mostly no pointersquot; quot;Mostly no GPFquot; Forget hunting memory leaks
  • 37. Class Version Management Real Life: Two people at two places write two pieces of software A's class builds on B's class B implements a method CalcResult Next version, A also adds CalcResult Q: Does B want CalcResult to be an override of A's ? A: Unlikely. Solution: Must state intent when using inheritance Must specify override to override a method Can specify new virtual to never inherit from base
  • 38. Goodies: XML Comments Consistent, intrinsic way to create doc from code Triple-slash quot;///quot; comments are exported Extract full documentation during compile with /doc Comes with predefined schema Example: ///<summary> /// This function serves to calculate the /// overall value of the item including all /// taxes /// </summary> /// <remarks> /// Tax calculates in CalcTax() /// </remarks> public decimal GetTotalValue() { }
  • 39. Section 3: The Tools .NET Framework SDK—all you need to build apps C# compiler Visual debugger Nmake Visual Studio.NET—the productivity rocket Development environment optimized for C# Code wizards and templates Smart help
  • 40. .NET Framework SDK C# compiler (plus Visual Basic, C++, and JScript) All language features Runs from the command line Visual Debugger—GuiDebug Built on Visual Studio.NET technology Full access to runtime metadata Tools Nmake, security, configuration, IL Disassembler, ... Free for everyone
  • 41. Visual Studio.NET Built on the .NET Framework SDK Reinvention of the concept of Visual Studio®, now with: Multiple-language projects One integrated development environment for all languages and tasks Integrated tools: Visual Modeler, Database Management Perfect help integration: Dynamic Help, IntelliSense® Highest productivity for all: Rapid application development Large-scale projects
  • 42. Section 4: Putting It All Together Samples The Classic Start: quot;Hello World!quot; in C# Exploring C# Features in Duwamish Books
  • 43. Hello World namespace Sample { using System; public class HelloWorld { public HelloWorld() { } public static int Main(string[] args) { Console.WriteLine(quot;Hello World!quot;); return 0; } } }
  • 44. Hello World Anatomy Contained in its own namespace References other namespaces with quot;usingquot; Declares a publicly accessible application class Entry point is quot;static int Main( ... )quot; Writes quot;Hello World!quot; to the system console Uses static method WriteLine on System.Console
  • 45. Summary C# builds on the .NET Framework component model New language with familiar structure Easy to adopt for developers of C, C++, Java, and Visual Basic applications Fully object oriented Optimized for the .NET Framework
  • 47. To C# from Visual Basic A very brief introduction to the C language family syntax for Visual Basic developers
  • 48. C Core principles: Be brief. Be expressive. Relatively few and short keywords Uses symbol ASCII characters instead of words Core element: quot;{quot; The Block quot;}quot; Code groups for structural or flow-control elements Blocks in Visual Basic Blocks in C Sub Xyz() void Xyz() { 'Code /*Code*/ End Sub } If MyVal=0 Then if (MyVal==0) { 'Code /*Code*/ End If }
  • 49. Statements All statements (quot;do that!quot;) are inside blocks Every statement is terminated with a semicolon quot;;quot; White space, line breaks, tabs are not significant May have many statements on one line Statements may be split across lines Statements: Just as legal: This too: #define/**/X char*d=quot;X0[!4cM,!quot; quot; 4cK`*!4cJc(!4cHg&!4c$jquot; quot;8f'!&~]9e)!'|:d+!)rAc-!*m*quot; quot; :d/!4c(b4e0!1r2e2!/t0e4!-y-c6!quot; a = add( 2, 3 ); a= quot; +|,c6!)f$b(h*c6!(d'b(i)d5!(b*a'`&cquot; quot;)c5!'b+`&b'c)c4!&b-_$c'd*c3!&a.h'd+quot; quot;d1!%a/g'e+e0!%b-g(d.d/!&c*h'd1d-!(d%g)quot; quot;d4d+!*l,d7d)!,h-d;c'!.b0c>d%!A`Dc$![7)35Equot; quot;!'1cA,,!2kE`*!-s@d(!(k(f//g&!)f.e5'f(!+a+)quot; quot;f%2g*!?f5f,!=f-*e/!<d6e1!9e0'f3!6f)-g5!4d*bquot; quot;+e6!0f%k)d7!+~^'c7!)z/d-+!'n%a0(d5!%c1a+/d4quot; quot;!2)c9e2!9b;e1!8b>e/! 7cAd-!5fAe+!7fBe(!quot; quot;8hBd&!:iAd$![7S,Q0!1 bF 7!1b?'_6!1c,8b4quot; quot;!2b*a,*d3!2n4f2!${4 f. '!%y4e5!&f%quot; q = a – 1; add quot;d-^-d7!4c+b)d9!4c-a 'd :!/i('`&dquot; quot;;!+l'a+d<!)l*b(d=!' m- a &d>!&d'quot; quot;`0_&c?!$dAc@!$cBc@!$ b < ^&d$`quot; quot;:!$d9_&l++^$!%f3a' n1 _ $ !&quot; quot;f/c(o/_%!(f+c)q*c %! * f &d+quot; quot;f$s&!-n,d)n(!0i- c- k) ! 3dquot; quot;/b0h*!H`7a,![7* i] 5 4 71quot; quot;[=ohr&o*t*q*`*d *v *r ; 02quot; quot;7*~=h./}tcrsth &t : r 9bquot; out( q ); (2,3 quot;].,b-725-.t--// #r [ < t8-quot; quot;752793? <.~;b ].t--+r / # 53quot; quot;7-r[/9~X .v90 <6/<.v;-52/={ k gohquot; quot;./}q; u vto hr `.i*$engt$ $ ,bquot; quot;;$/ =t ;v; 6 =`it.`;7=` : ,b-quot; quot;725 = / o`. .d ;b]`--[/+ 55/ }oquot; quot;`.d : - ?5 / }o`.' v/i]q - quot; quot;-[; 5 2 =` it . o;53- . quot; quot;v96 <7 / =o : d =oquot; q--; );q=a quot;--/i ]q-- [; h. / = quot; quot;i]q--[ ;v 9h ./ < - quot; quot;52={cj u c&` i t . o ; quot; quot;?4=o:d= o-- / i ]q - quot; quot;-[;54={ cj uc& i]q - -quot; quot;[;76=i]q[;6 =vsr u.i / ={quot; quot;=),BihY_gha ,)0 quot; , o [ 3217];int i, r,w,f , b ,x , p;n(){return r <X X X X X return; –1;out 768?d[X(143+ X r++ + *d ) % 768]:r>2659 ? 59: ( x = d [(r++-768)% X 947 + 768] ) ? x^(p?6:0):(p = 34 X X X ) ;}s(){for(x= n (); ( x^ ( p ?6:0))==32;x= n () ) ;return x ; } void/**/main X () { r = p =0;w=sprintf (X X X X X X o ,quot;char*d=quot;); for ( f=1;f < * d (q);q—- +143;)if(33-( b=d [ f++ X ] ) ){if(b<93){if X(! p ) o [w++]=34;for X(i = 35 + (p?0:1);i<b; i++ ) o [w++]=s();o[ w++ ] =p?s():34;} else X {for(i=92; i<b; i ++)o[w++]= 32;} } else o [w++ ] ;return; =10;o [ w]=0 ; puts(o);} quot;This tooquot; Credits: Don Yang, Winner quot;Best Layoutquot; International Obfuscated C Contest http://www.ioccc.org
  • 50. Declaration Principles Core declaration principle: quot;What then whoquot; What: data type or declaration keyword Types: int, string, decimal, float Keywords: enum, struct, class Who: user-defined identifier Must begin with a letter, may contain numbers, quot;_quot; Attention: All identifiers are case sensitive Variable declarations: Structure declaration: int MyValue; string MyName; struct Point { int x; int y; Function declaration: } int MyFunc(string Arg);
  • 51. Operators Arithmetic binary operators quot;oprd1 operator oprd2quot; add (+), subtract (-), divide (/), multiply (*) Modulo (%) a=b%c; instead of a=b mod c unary operators quot;oprd1 operatorquot; increment (++), decrement (--) i++ instead of i=i+1 Logical and (&&), or (||), not(!) Bitwise and (&), or(|), xor (^), not (~) Relational equal (==), not equal (!=), less (<) greater (>), less equal (<=), greater equal (>=)
  • 52. Expressions Boolean expressions Evaluate to true or false (2 == 1) is false, (2 > 1) is true Arithmetic expressions like Visual Basic 1 + 2 * (6 / 2) Assignment a = 1; also at declaration time: int a = 0; a += 4; equivalent to a = a + 4; a *= 2; equivalent to a = a * 2; works with all binary operators.
  • 53. Flow Control Conditional execution of code blocks: if (<expression>) <block> [else <block>]; Selective execution of code blocks: switch(<variable>) { case <value>: <statements>; break; } switch (i) { if (i == 0 ) case 0: { Console.Write(quot;Thisquot;); Console.Write(quot;Thisquot;); break; } case 1: else Console.Write(quot;Thatquot;); { break; Console.Write(quot;Thatquot;); default: }; Console.Write(quot;Elsequot;); break; }
  • 54. Loops Counted loops for(<pre>;<while>;<increment>) <block> <pre>: Setting precondition quot;i=0quot; <while>: Testing continuation condition quot;i<10quot; <increment>: Calculating counter state quot;i++quot; While loops while (<expression>) <block> do <block> while (<expression>); for (i=0; i< 10; i++ ) while ( !MyFile.EOF ) { { Console.Write(i); Console.Write(MyFile.Read()); } }
  • 55. Other Noteworthy Things ... The data type quot;voidquot; means quot;no typequot; method void func(int a) returns nothing Like a quot;Subquot; in Visual Basic method int func(void) has no arguments C has pointers. In C# you do not need them Don't worry about them Reference and value types are clearly defined ref keyword for values by reference Very few keywords and intrinsic functionality quot;Cquot; languages rely heavily on run-time libraries Example: Math.Pow(a,b) instead of a^b
  • 56. Legal Notices Unpublished work. © 2001 Microsoft Corporation. All rights reserved. Microsoft, IntelliSense, JScript, Visual Basic, Visual Studio, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.