Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

CSharp Introduction

VIEWS: 51 PAGES: 19

Introduction to the C# programming language.The course contains basic elements and structure of this programming language, can be useful as starting point for beginner developers and as reference for experienced developers.

More Info
									C# CSharp Introduction

Ivica Gjorgjievski - IGProgram                              This tutorial is free for use and distribution as it is, cannot
igprogram@hotmail.com                                       be changed or used for commercial purposes.
www.igprogram.webs.com



Content
Introduction .......................................................................................................................................... 1
1    Comments .................................................................................................................................... 2
2    Keywords ..................................................................................................................................... 2
3    Types ............................................................................................................................................ 3
4    Identifiers ..................................................................................................................................... 5
5    Constants ...................................................................................................................................... 5
6    Variables ...................................................................................................................................... 6
7    Operators ...................................................................................................................................... 6
8    Expressions .................................................................................................................................. 8
9    Statements .................................................................................................................................... 9
10 Methods...................................................................................................................................... 10
11 Enumerators ............................................................................................................................... 12
12 Arrays ......................................................................................................................................... 12
13 Structures ................................................................................................................................... 13
14 Classes ........................................................................................................................................ 14
15 Interfaces .................................................................................................................................... 17
16 Namespaces ................................................................................................................................ 18



Introduction
This tutorial is introduction to the C# programming language.
The tutorial contains basic elements and structure of this programming language, can be useful as
starting point for beginner developers and as reference for experienced developers.

C# CSharp is modern object oriented programming language. It includes also support for
component oriented programming and has unified type system.

using System;
namespace Introduction
{
  class Program
  {
     static void Main()
     {
        Console.WriteLine("Hello from C# ");
     }
  }
}

Result:
Hello from C#


                                                                                                                                                       1
Build:
 Save the code with Notepad in text file c:\hello.cs
 From Command Prompt build the program with C# compiler csc.exe
 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe "c:\hello.cs"
 Execute generated program, double click on c:\hello.exe


Links:
 Net Framework: http://www.microsoft.com/netframework
 Visual C# Express: http://www.microsoft.com/express
 Sharp Develop: http://sharpdevelop.com




1      Comments
Comments are descriptions for the code and are useful for the programmer, but are not used by the
program.

C# has three categories of comments:
 Single line comments start with the characters //
 Delimited comments start with the characters /* and end with */
 Documentation comments start with the characters ///


using System;
namespace Comments
{
  /// <summary>
  /// Documentation comment for the class
  /// </summary>
  class Program
  {
      /// <summary>
      /// Doccumentation comment for the method
      /// </summary>
      /// <param name="args"></param>
      static void Main(string[] args)
      {
          // Single line comment
          Console.WriteLine("Hello from C# "); /* Delimited comment */
      }
  }
}




2      Keywords
Keywords are reserved words by the programming language.
In code they can be used only for their purpose, cannot be used as identifiers except if not
proceeded by @ character.


                                                                                                    2
C# keywords:
abstract     as              base           bool
break        by3             byte           case
catch        char            checked        class
const        continue        decimal        default
delegate     do              double         descending3
explicit     event           extern         else
enum         false           finally        fixed
float        for             foreach        from3
goto         group3          if             implicit
in           int             interface      internal
     3
into         is              lock           long
new          null            namespace      object
operator     out             override       orderby3
params       private         protected      public
readonly     ref             return         switch
struct       sbyte           sealed         short
sizeof       stackalloc      static         string
       3
select       this            throw          true
try          typeof          uint           ulong
unchecked unsafe             ushort         using
var3         virtual         volatile       void
while        where3          yield2

2 - C# 2.0 Keywords
3 - C# 3.0 Keywords




3      Types
Types define the type/model of elements used by the program, for example numeric or text.

C# has value types, reference types and pointer types (only in unsafe code).

Variables of value types directly contain their data, variables of reference types store references to
their data.

Value types are simple types, enum types, struct types and nullable types.
Reference types are class types, interface types, array types, and delegate types.

C# type system:
 Category                           Description
 Value          Simple types        Signed integral: sbyte, short, int, long
 types                              Unsigned integral: byte, ushort, uint, ulong
                                    Unicode characters: char
                                    IEEE floating point: float, double
                                    High-precision decimal: decimal
                                    Boolean: bool
                 Enum types         User-defined types of the form enum E {...}

                                                                                                         3
                 Struct types       User-defined types of the form struct S {...}
                 Nullable types     Extensions of all other value types with a null value
 Reference       Class types        Ultimate base class of all other types: object
 types                              Unicode strings: string
                                    User-defined types of the form class C {...}
                 Interface types    User-defined types of the form interface I {...}
                 Array types        Single- and multi-dimensional, for example, int[] and
                                    int[,]
                 Delegate types     User-defined types of the form e.g. delegate int D(...)



C# numeric types:
 Category      Bits     Type        Range/Precision
 Signed        8        sbyte       –128...127
 integral      16       short       –32,768...32,767
               32       int         –2,147,483,648...2,147,483,647
               64       long        –
                                    9,223,372,036,854,775,808...9,223,372,036,854,775,807
 Unsigned        8      byte        0...255
 integral        16     ushort      0...65,535
                 32     uint        0...4,294,967,295
                 64     ulong       0...18,446,744,073,709,551,615
 Floating        32     float       1.5 × 10−45 to 3.4 × 1038, 7-digit precision
 point           64     double      5.0 × 10−324 to 1.7 × 10308, 15-digit precision
 Decimal         128    decimal     1.0 × 10−28 to 7.9 × 1028, 28-digit precision


using System;
namespace Types
{
  class Program
  {
     static void Main(string[] args)
     {
        int numeric = 5;            // Type int
        string text = "Text data"; // Type string
        Console.WriteLine("numeric:{0} text: {1}", numeric, text);
     }
  }
}


Result:
numeric:5 text: Text data


Conversion is process in which value of one type is converted to other type. The new type need to
have storage to contain the new value, otherwise the error is raised.

byte value1 = 255;
int value2 = (int)value1; // (int) convert value1 from byte to int


                                                                                                    4
Boxing and unboxing are processes in which value types can be treated as objects.
It is similar to conversion but in memory value types are moved from stack memory to heap
memory of the computer.

int value1 = 123;          // Value type
object object1 = value1; // Boxing in object
int value2 = (int)object1; // Unboxing in value type




4      Identifiers
Identifiers identify elements in the code defined by the programmer.
They have to be simple and describe the elements that represent, cannot be reserved keywords.


using System;
namespace Identifiers // Identifiers is identifier of namespace
{
  class Program // Program is identifier of class
  {
     static void Main(string[] args) // Main is identifier of method
     {
        int numeric = 5;            // numeric is identifier of variable
        string text = "Text data"; // text is identifier of variable
        Console.WriteLine("numeric:{0} text: {1}", numeric, text);
     }
  }
}


Result:
numeric:5 text: Text data




5      Constants
Constant represents a constant value that can be computed at compile time and don't change during
program execution.

Constants are declared by const keyword followed by type and identifier.



using System;
namespace Constants
{
  class Program
  {
     static void Main(string[] args)
     {

                                                                                                    5
            const int numeric = 5;            // Constant value
            const string text = "Text data"; // Constant value
            numeric = 6; // Error ! constant value cannot change

            Console.WriteLine("numeric:{0} text: {1}", numeric, text);
        }
    }
}




6           Variables
Variables represent storage locations in memory of the computer.

Variables have type that determines what values can be stored and also have identifier that
identifies the variable in the code.

Variable value must be assigned before it can be obtained. The value of a variable can be changed
in the program.

C# has different categories of variables: static variables, instance variables, array elements, value
parameters, reference parameters, output parameters, and local variables.


using System;
namespace Variables
{
  class Program
  {
     public static int variable1 = 1; // variable1 is static variable (class variable)
     public int variable2 = 2;        // variable2 is instance variable (object variable)

        static void Main(string[] args) // args is parameter variable
        {
           int variable3 = 3;    // variable3 is local variable, of this method
           variable3 = 5;        // Variable can change its value

            Console.WriteLine(variable3);
        }
    }
}


Result:
5




7           Operators
Operator applies operation on values.

                                                                                                        6
For example in variable = 1 + 2 the operator + sum the values 1 and 2, the operator = assign the
result to the variable.


C# operators in order of precedence from highest to lowest:

 Category              Operators
 Primary               x.y f(x) a[x] x++ x-- new
                       typeof default checked unchecked delegate
 Unary                 + - ! ~ ++x --x (T)x
 Multiplicative        * / %
 Additive              + -
 Shift                 << >>
 Relational and type   < > <= >= is as
 testing
 Equality              == !=
 Logical AND           &
 Logical XOR           ^
 Logical OR            |
 Conditional AND       &&
 Conditional OR        ||
 Null coalescing       ??
 Conditional           ?:
 Assignment and        = *= /= %= += -= <<= >>= &= ^= |=
 lambda expression     =>


 Category              Expression            Description
 Primary               x.m                   Member access
                       x(...)                Method and delegate invocation
                       x[...]                Array and indexer access
                       x++                   Post-increment
                       x--                   Post-decrement
                       new T(...)            Object and delegate creation
                       new T(...){...}       Object creation with initializer
                       new {...}             Anonymous object initializer
                       new T[...]            Array creation
                       typeof(T)             Obtain System.Type object for T
                       checked(x)            Evaluate expression in checked context
                       unchecked(x)          Evaluate expression in unchecked context
                       default(T)            Obtain default value of type T
                       delegate {...}        Anonymous function (anonymous method)
 Unary                 +x                    Identity
                       -x                    Negation
                       !x                    Logical negation
                       ~x                    Bitwise negation
                       ++x                   Pre-increment
                       --x                   Pre-decrement
                       (T)x                  Explicitly convert x to type T
 Multiplicative        x*y                   Multiplication
                       x/y                   Division

                                                                                                   7
                         x%y                   Remainder
 Additive                x+y                   Addition, string concatenation, delegate
                                               combination
                         x–y                   Subtraction, delegate removal
 Shift                   x << y                Shift left
                         x >> y                Shift right
 Relational and type     x<y                   Less than
 testing                 x>y                   Greater than
                         x <= y                Less than or equal
                         x >= y                Greater than or equal
                         x is T                Return true if x is a T, false otherwise
                         x as T                Return x typed as T, or null if x is not a T
 Equality                x == y                Equal
                         x != y                Not equal
 Logical AND             x&y                   Integer bitwise AND, boolean logical AND
 Logical XOR             x^y                   Integer bitwise XOR, boolean logical XOR
 Logical OR              x|y                   Integer bitwise OR, boolean logical OR
 Conditional AND         x && y                Evaluates y only if x is true
 Conditional OR          x || y                Evaluates y only if x is false
 Null coalescing         X ?? y                Evaluates to y if x is null, to x otherwise
 Conditional             x?y:z                 Evaluates y if x is true, z if x is false
 Assignment or           x=y                   Assignment
 anonymous               x op= y               Compound assignment; supported operators are
 function                                      *= /= %= += -= <<= >>= &= ^= |=
                         (T x) => y            Anonymous function (lambda expression)



using System;
namespace Operators
{
  class Program
  {
     static void Main(string[] args)
     {
        // The operator + sum the values 1 and 2
        // The operator = assign the result to the variable.
        int variable = 1 + 2;
        Console.WriteLine(variable);
     }
  }
}


Result:
3




8         Expressions
Expression is a sequence of operators and operands.

                                                                                              8
The operators of one expression indicate which operations to apply to the operands.

When one expression contains multiple operators, the precedence of the operators controls the order
in which the individual operators are evaluated.
For example the expression x + y * z is evaluated as x + (y * z) because the * operator has higher
precedence than the + operator.


using System;
namespace Expressions
{
  class Program
  {
     static void Main(string[] args)
     {
        int variable1 = 1 + 2 * 3; // Evaluated as 1 + 6
        int variable2 = (1 + 2) * 3; // Evaluated as 3 * 3
        Console.WriteLine("variable1: {0} variable2: {1}", variable1, variable2);
     }
  }
}


Result:
variable1: 7 variable2: 9




9      Statements
Statements define the actions of the program, C# supports different kinds of statements:

Selection statements are used to select one of possible statements for execution based on the value
of some expression. In this group are if and switch.

Iteration statements are used to repeatedly execute an embedded statement. In this group are while,
do, for and foreach.

Jump statements are used to transfer control. In this group are break, continue, goto, throw, return,
and yield.

The checked and unchecked statements are used to control the overflow checking context for
integral type arithmetic operations and conversions.

The lock statement is used to obtain the mutual exclusion lock for a given object, execute a
statement, and then release the lock.

The using statement is used to obtain a resource, execute a statement, and then dispose of that
resource.




                                                                                                        9
The try...catch…finally statements are used to catch exceptions that occur during execution of a
block and to specify finalization code that is always executed, whether an exception occurred or
not.

A block permits multiple statements to be written in contexts where a single statement is allowed. A
block consists of a list of statements written between the delimiters { and }.

Declaration statements are used to declare local variables and constants.

Expression statements are used to evaluate expressions.


using System;
namespace Statements
{
  class Program
  {
     static void Main(string[] args)
     {
        int variable1 = 3; // Declaration statement

            if (variable1 == 3) // if statement
            {
               Console.WriteLine("variable1: {0}", variable1);
            }

            for (int index = 0; index < 3; index++) // for statement
            {
               Console.WriteLine("index:{0}", index);
            }
        }
    }
}


Result:
variable1: 3
index:0
index:1
index:2




10          Methods
Method is set of statements enclosed in block, can have attributes modifiers return type name and
parameters.


Return type specify the type of the value computed and returned by the method
If this type is void then method do not return nothing, otherwise method must return value specified
by return type with the keyword return.


                                                                                                    10
Parameters are used to pass values or variable references to methods.
There are four kinds of parameters: value parameters, reference parameters, output parameters, and
parameter arrays.

Value parameter is used for input parameter passing. Modifications to a value parameter do not
affect the argument that was passed for the parameter.

Reference parameter is used for both input and output parameter passing. A reference parameter is
declared with the ref modifier. Modifications to a value parameter do not affect the argument that
was passed for the parameter.

Output parameter is used for output parameter passing. An output parameter is similar to a reference
parameter except that the initial value of the caller provided argument is unimportant. An output
parameter is declared with the out modifier.

A parameter array permits a variable number of arguments to be passed to a method.


using System;
namespace Methods
{
  class Program
  {
     static void Main(string[] args)
     {
        int var1 = 1;
        int var2 = 2;
        int var3 = 3;

            // Call the method passing parameters and geting the result
            int result = Method1(var1, ref var2, out var3);

            Console.WriteLine("var1: {0} var2: {1} var3: {2} return value: {3}",
              var1, var2, var3, result);
        }

        // Method1 has 3 parameters and return type of int
        static int Method1(int par1, ref int par2, out int par3)
        {
           par2 = 4;        // Reference parameter
           par3 = 5;        // Output parameter
           return 6;        // Return value
        }

    }
}


Result:
var1: 1 var2: 4 var3: 5 return value: 6




                                                                                                 11
11        Enumerators
Enumerator is a value type that declares a set of named constants.
Default type for enumerator elements is int and they start with index 0.


using System;
namespace Enumerators
{
  // Declare enumerator
  enum Enum1 { Value1, Value2, Value3 }

    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine(Enum1.Value1 != Enum1.Value2);
          Console.WriteLine((int)Enum1.Value2);
       }
    }
}


Result:
True
1




12        Arrays
Array is a data structure that contains variables that are accessed through indices.

The variables contained in an array also called the elements of the array, are all of the same type.
The index of array elements is zero based.

The new permits the initial values of the array elements to be specified using an array initializer, it
is a list of expressions written between the delimiters { and }.

C# has single dimensional, multi dimensional and jagged arrays.


using System;
namespace Arrays
{
  class Program
  {
     static void Main(string[] args)
     {
        // Define and initialize single-dimensional array
        int[] array1 = new int[] { 1, 2, 3 };

          // Define single-dimensional array
          int[] array2 = new int[5];

                                                                                                       12
            array2[0] = 4; // Initialize some elements from array2
            array2[1] = 5;

            // Define multidimensional array
            int[,] array3 = new int[5, 5];
            array3[0,0] = 6; // Initialize some elements from array3
            array3[0,1] = 7;

            // Define jagged array
            int[][] array4 = new int[5][];
            array4[0] = new int[10]; // Initialize some elements from array4
            array4[1] = new int[15];
            array4[0][0] = 8;
            array4[0][1] = 9;

            // Use the arrays
            Console.WriteLine("array1[0]: {0}", array1[0]);
            Console.WriteLine("array2[0]: {0}", array2[0]);
            Console.WriteLine("array3[0,0]: {0}", array3[0,0]);
            Console.WriteLine("array4[0][0]: {0}", array4[0][0]);
        }
    }
}


Result:
array1[0]: 1
array2[0]: 4
array3[0,0]: 6
array4[0][0]: 8




13          Structures
Structures are types that can contain data and function members, unlike classes structures are value
types and directly contain their values.

Variable of type struct directly stores data (in stack memory), variable of type class store reference
to a dynamically allocated object (in heap memory of the computer).

Structures are particularly useful for small data structures and for performance when it is needed
large number of memory allocations.

With structures struct types the variables each have their own copy of data, and it is not possible for
operations on one variable to affect the other.

With classes class types it is possible for two variables to reference the same object and operations
on one variable to affect the object referenced by the other variable.




using System;

                                                                                                     13
namespace Structures
{
  // Declare the structure, changing type from struct to class will change the program result
  struct Point
  {
     public int x; // Structure variables
     public int y;

        // Structure construcor
        public Point(int x, int y)
        {
           this.x = x; // Initialize structure variables
           this.y = y;
        }
    }


    class Program
    {
       static void Main(string[] args)
       {
          // Initialize object of type Point
          Point point = new Point(1, 2);

            // If Point is of type struct point2 variable is copy of point
            // If Point is of type class point2 variable is reference to the same object point
            Point point2 = point;

            // If Point is of type struct point2.x = 11 change only value of point2.x
            // If Point is of type class point2.x = 11 change also value of point.x
            point2.x = 11;

            // Value of point.x depends if Point is defined as type struct or class
            Console.WriteLine("point.x: {0}", point.x);
            Console.WriteLine("point2.x: {0}", point2.x);
        }
    }
}


Result:
point.x: 1
point2.x: 11




14          Classes
Class is a type that combines data methods events and other elements in a single unit.

Class provides a definition for dynamically created instances of the class, also known as objects,
this objects are dynamically allocated in the heap memory of the computer.



                                                                                                     14
With class types it is possible for two variables to reference the same object and operations on one
variable to affect the object referenced by the other variable.

Classes support inheritance and polymorphism, mechanisms by which derived classes can extend
and specialize base classes.

Class declaration starts with a header that specifies the attributes and modifiers of the class, the
name of the class, the base class (if given), and the interfaces implemented by the class.
The header is followed by the class body, which consists of a list of member declarations written
between the delimiters { and }.

Instances of classes are created using the new operator, which allocates memory for a new instance,
invokes a constructor to initialize the instance, and returns a reference to the instance.

The memory occupied by an object is automatically reclaimed when the object is no longer in use.
It is not necessary or possible to explicitly de allocate objects in C#.

The members of a class are either static members or instance members. Static members belong to
classes, and instance members belong to objects (instances of classes).

 Member               Description
 Constants            Constant values associated with the class
 Fields               Variables of the class
 Methods              Computations and actions that can be performed by the class
 Properties           Actions associated with reading and writing named properties of the class
 Indexers             Actions associated with indexing instances of the class like an array
 Events               Notifications that can be generated by the class
 Operators            Conversions and expression operators supported by the class
 Constructors         Actions required to initialize instances of the class or the class itself
 Destructors          Actions to perform before instances of the class are permanently discarded
 Types                Nested types declared by the class



Each member of a class has an associated accessibility, which controls the regions of program text
that able to access the member. There are five possible forms of accessibility.

 Accessibility                 Meaning
 public                        Access not limited
 protected                     Access limited to this class or classes derived from this class
 internal                      Access limited to this program
 protected internal            Access limited to this program or classes derived from this class
 private                       Access limited to this class


Inheritance means that a class implicitly contains all members of its base class type, except for the
constructors and destructors of the base class.

Inheritance is transitive. If C is derived from B, and B is derived from A, then C inherits the
members declared in B as well as the members declared in A.

Derived class extends its direct base class. A derived class can add new members to those it
inherits, but it cannot remove the definition of an inherited member.

                                                                                                       15
using System;
namespace Classes
{
  // Declaration of Class1
  class Class1
  {
     public void Method1()
     {
       Console.WriteLine("Class1.Method1");
     }
  }

    // Class2 inherit from Class1
    class Class2 : Class1
    {
       public string Field1 = ""; // Public field / variable

        // Constructor
        public Class2(string value1)
        {
           this.Field1 = value1;
        }

        public void Method2()
        {
          Console.WriteLine("Class2.Method2");
        }

        public static void Method3()
        {
          Console.WriteLine("Class2.Method3 static");
        }
    }


    class Program
    {
       static void Main(string[] args)
       {
          // Create instance of Class2 passing text in the constructor
          Class2 object2 = new Class2("Hello from classes");

            object2.Method1(); // Call inherited method from base Class1
            object2.Method2(); // Call method of the instance
            Class2.Method3(); // Call static method of the class
            Console.WriteLine("object2.Field1: {0}", object2.Field1); // Print instance field value
        }
    }
}


Result:
Class1.Method1

                                                                                                      16
Class2.Method2
Class2.Method3 static
object2.Field1: Hello from classes




15        Interfaces
Interface defines the members that must be supplied by classes or structures that implement the
interface.

Interfaces does not provide implementations of the members it defines, it only specifies the
members that must be supplied by classes or structures that implement the interface.

Interface can contain methods, properties, events, and indexers.
Interfaces can be used in multiple inheritance, class or structure can inherit multiple interfaces.


using System;
namespace Interfaces
{
  interface Interface1 { void Method1(); }
  interface Interface2 { void Method2(); }

  // Define Interface3, inherit from Interface1 and Interface2
  interface Interface3 : Interface1, Interface2
  {
     void Method3();
  }

  // Define Class1, inherit from Interface3 and implement the methods
  class Class1 : Interface3
  {
     public void Method1() { Console.WriteLine("Class1.Method1"); }
     public void Method2() { Console.WriteLine("Class1.Method2"); }
     public void Method3() { Console.WriteLine("Class1.Method3"); }
  }

  class Program
  {

      static void Main(string[] args)
      {
         // Create instance of Class1
         Class1 object1 = new Class1();

          // Point the object with interface that it implement
          Interface3 pointer = object1;

          pointer.Method1(); // Call the object method with interface pointer
          pointer.Method2(); // Call the object method with interface pointer
          object1.Method3(); // Call the object method with object instance
      }
  }

                                                                                                      17
}


Result:
Class1.Method1
Class1.Method2
Class1.Method3




16     Namespaces
Namespaces are organizational units for program elements.

C# programs are organized using namespaces. Namespaces are used both as an internal
organization for a program, and as an external organization for presenting program elements that
are exposed to other programs.

A using namespace directive imports the types contained in a namespace into the immediately
enclosing compilation unit or namespace body, enabling the identifier of each type to be used
without qualification.

A namespace declaration consists of the keyword namespace, followed by a namespace name and
body, optionally followed by a semicolon.

Namespaces are open ended, and two namespace declarations with the same fully qualified name
contribute to the same declaration space


// Import namespace System with using directive
// This namespace contains simple types as int, and lot others ...
using System;

namespace Namespace1
{
  class Class1
  {
     public static void Method1()
     {
       Console.WriteLine("Namespace1.Class1.Method1");
     }
  }
}

namespace Namespaces
{
  class Program
  {
     static void Main(string[] args)
     {
        // Use full name for Class1 becouse Namespace1
        // was not imported with using directive
        Namespace1.Class1.Method1();
     }

                                                                                                   18
    }
}



Result:
Namespace1.Class1.Method1




Ivica Gjorgjievski - IGProgram   This tutorial is free for use and distribution as it is, cannot
igprogram@hotmail.com            be changed or used for commercial purposes.
www.igprogram.webs.com




                                                                                                   19
.igprogram.webs.com




                                                                                                   19

								
To top