SlideShare a Scribd company logo
1 of 15
bogotobogo
Bogotobogo
contact@bogotobogo.com
                                      Home | Sitemap | Contact Us
                                                  Home | About Us | Products | Our Services | Contact Us
                                                                                    Gif |JavaApplet/Web
Start | Flash | ShockWave | SVG | iPhone/iPad | Android | HTML5 |Algorithms | News | C++ | Java | PHP
                                                               | Design Patterns | Python | C# | Forums
                                                                   Search




                                Introduction




                                  List of C# 4.0 Tutorials

                                            .NET Framework
                                     Introduction - My First C# Code
                                       System Members and Data
                                                Modifiers
                                                  Array
Enumeration (Enums)
                                Value and Reference Types
                               Constructor and this Keyword
                                       static Keyword
                                   Encapsulation Services
                                         Inheritance
                                       Inheritance II
                                       Polymorphism
                                          Interfaces
                                          Delegates
                                       System.Object
                                            Events
                    Multi Threading I - Introduction and Simple Thread
                Multi Threading II - ThreadStart/ParameterizedThreadStart,
                             Foreground/Background Threads
                    Multi Threading III - Concurrency, Synchronization
                      Networking I - PORT, IPv4/IPv6, TCP/UDP, URI
                 Networking II - WebRequest/WebResponse, WebClient




                               Introduction
    C# is a multi-paradigm programming language encompassing imperative,
declarative, functional, generic, object-oriented, and component-oriented programming
                                        disciplines.

    It was developed by Microsoft within the .NET initiative and later approved as a
       standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the
programming languages designed for the Common Language Infrastructure (CLI).




C# is intended to be a simple, modern, general-purpose, object-oriented programming
 language. Its development team is led by Anders Hejlsberg. The most recent version
                   is C# 4.0, which was released on April 12, 2010.
What's new in C# 4.0

    C# 4.0 is the latest version, which was released in April 11, 2010. Microsoft has
released the 4.0 runtime and development environment Visual Studio 2010. The major
 focus of C# 4.0 is interoperability with partially or fully dynamically typed languages
         and frameworks, such as the Dynamic Language Runtime and COM.



                                     Your Ad Here



                                Here are new features:

                                Dynamic member lookup
      A new pseudo-type dynamic is introduced into the C# type system. It is treated
        as System.Object, but in addition, any member access (method call, field,
         property, or indexer access, or a delegate invocation) or application of an
      operator on a value of such type is permitted without any type checking, and its
           resolution is postponed until run-time. This is known asDuck typing.



               Covariant and contravariant generic type parameters
        Generic interfaces and delegates can have their type parameters marked
         as covariant or contravariant, using keywords out and in, respectively.
        These declarations are then respected for type conversions, both implicit and
                        explicit, and both compile-time and run-time.



                        Optional ref Keyword when using COM
      The ref keyword for callers of methods is now optional when calling into methods
                                 supplied by COM interfaces.



                     Optional parameters and named arguments
      C# 4.0 introduces optional parameters with default values as seen in Visual Basic
                                        and C++.
Indexed properties
      Indexed properties (and default properties) of COM objects are now recognized,
                         but C# objects still do not support them.



                      Visual Studio Command Prompt

You can invoke the C# compiler by typing the name of its executable file, csc.exe on
  the command line. If you use the Visual Studio Command Prompt (available as a
shortcut on the start menu under Visual Studio Tools), all the necessary environment
     variables are set for you. Otherwise, you must adjust your path in order to
enable csc.exe to be invoked from any subdirectory on your computer. If you do not
                  use the Visual Studio Command Prompt, you must
   run vsvars32.bat under C:Program Files (x86)Microsoft Visual Studio
  10.0Common7Tools to set the appropriate environment variables to support
                                 command line builds.

                         Let's start with Visual Studio 2010:
          Start -> Programs -> Visual Studio 2010 -> Visual Studio Tools.

                                   Then, type in

                                      csc -?

                                      We get:
If we want to make it work on other command prompt, we should set the new path.
                             For my system the paths are:

           C:WindowsMicrosoft.NETFramework64v4.0.30319
       C:Program Files (x86)Microsoft SDKsWindowsv7.0ABin
   C:Program Files (x86)Microsoft Visual Studio 10.0SDKv3.5Bin

  Once you have updated your Path variable, close all dialog boxes and any currently
 opened Console windows to commit the settings. You should now be able to execute
 csc.exe and other .NET tools from any Command prompt. To test, enter the following
                                     commands:

                                             csc -?
                                            ildasm -?

We can check it's working if we see the same output as the one running from the Visual
                                     Studio Prompt.



                                Simple Command Line C#

   Option                                            Description

                  This option is used to specify the name of the assembly to be created. By
/out
                  default, the assembly name is the same as the name of the initial input *.cs file.

                  This option is used to specify the name of the assembly to be created. By
/target:exe
                  default, the assembly name is the same as the name of the initial input *.cs file.

/target:library   This option builds a single-file *.dll assembly

/target:module This option builds a module. Modules are elements of multifile assemblies.

                  Although we are free to build graphical user interface-based applications using
/target:winexe
                  the target:exe. Modules are elements of multifile assemblies.



                                  Compiles File.cs producing File.exe

                                      csc /target:exeFile.cs


                        Compiles File.cs using abbreviation producing File.exe

                                          csc /t:exeFile.cs
Compiles File.cs producing File.exe because /t:exe is the default output.

                                        cscFile.cs


                              Compiles File.cs producing File.dll

                              csc /target:libraryFile.cs


                         Compiles File.cs and creates MyCSharp.exe:

                            csc /out:MyCSharp.exe File.cs


         Compiles all the C# files in the current directory, with optimizations on and
                     defines the DEBUG symbol. The output is File2.exe

                csc /define:DEBUG /optimize /out:File2.exe *.cs


        Compiles all the C# files in the current directory producing a debug version of
                       File2.dll. No logo and no warnings are displayed

       csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs


        Compiles all the C# files in the current directory to Something.useful (a DLL):

                 csc /target:library /out:Something.useful *.cs


                        C# Compiler vs. C++ Compiler

There are no object (.obj) files created as a result of invoking the C# compiler; output
 files are created directly. As a result of this, the C# compiler does Not need a linker




                              My First C# Program

                               Here is our first C# code:
// Program.cs
                                using System;
                      usingSystem.Collections.Generic;
                              usingSystem.Linq;
                              usingSystem.Text;

                         namespaceMyFirstCSharpCode
                                      {
                                class Program
                                        {
                       static void Main(string[] args)
                                          {
                                          }
                                        }
                                      }

A C# program consists of one or more type declarations. C# requires that all program
 be contained within a type (class, interface, structure, enumeration, delegate etc.)
definition. In other words, all data members and methods must be contained within a
         type definition. In the above example, only the class type is declared.

             The code is created as a new Console Application project
                            named MyFirstCSharpCode.

          The program uses two namespaces. It creates a new namespace
   called MyFirstCSharpCode, and uses a predefined namespace called System.

   The method Main() is a member of class MyFirstCSharpCode and it's a special
 function used by the compiler as the starting point of the program. By default, Visual
  Studio names the class defining Main(). Here, it's the Program. So, the file name
         isProgram.cs. However, we are free to change this if we so choose.

 The class that defines the Main() method is termed the application object (which
       can be useful when performing unit tests), we must inform the compiler
 which Main() method should be used as the entry point via the /main option of the
                               command-line compiler.

Note that the signature of Main() is adorned with the static keyword. Static members
  are scoped to the class level rather than the object level and can thus be invoked
                 without the need to first create a new class instance.

In addition to the static keyword, this Main() method has a single parameter, which is
                                  an array of strings:

                                   string[] args
To compile the program, we can use Visual Studio or the command-line compiler. To
            use the command-line compiler, use the following command:

                                  cscProgram.cs

In this command, csc is the name of the command-line compiler and Program.cs is
                            the name of the source file.

                       Let's make the code more interesting:

                               // Program2.cs
                                using System;
                      usingSystem.Collections.Generic;
                              usingSystem.Linq;
                              usingSystem.Text;

                        namespaceMyFirstCSharpCode
                                     {
                              class Program2
                                       {
                     static void Main(string[] args)
                                         {
                  Console.WriteLine("My first C# code");
                    Console.WriteLine("Hello World");
                           Console.WriteLine();
                            Console.ReadLine();
                                         }
                                       }
                                     }

     In the new code, we make use of the Console class, which is defined within
 the System namespace. Among its set of members is the static WriteLine() which
  pumps a text string and carriage return to the standard output. We also make a call
toConsole.ReadLine() to ensure the command prompt launched by the Visual Studio
   2010 IDE remains visible during a debugging session until we press the Enter key.

                 Note that we have several methods for our Main():

                          static int Main(string[] args)
                                static void Main()
                                 static int Main()


                                   Error Code
The ability to return an int from Main() keeps C# consistent with other C-based
languages. By convention, returning the value 0indicates the program has terminated
     successfully, while another value such as -1 represents an error condition.

      On the Windows OS, an application's return value is stored within a system
environment variable named %ERRORLEVEL%. If we were to create an application
     that programmatically launches another executable, we can obtain the value
                          of%ERRORLEVEL% using the
              static System.Diagnostics.Process.ExitCode property.

   Given that an application's return value is passed to the system at the time the
  application terminates, it is obviously not possible for an application to obtain and
display its final error code while running. However, to illustrate how to view this error
       level upon program termination, begin by updating the Main() method:

                               // Program3.cs
                                using System;
                      usingSystem.Collections.Generic;
                              usingSystem.Linq;
                              usingSystem.Text;

                        namespaceMyFirstCSharpCode
                                     {
                              class Program3
                                       {
                       staticint Main(string[] args)
                                         {
                  Console.WriteLine("My first C# code");
                    Console.WriteLine("Hello World!");
                           Console.WriteLine();
                            Console.ReadLine();
                                return -1;
                                         }
                                       }
                                     }

Let's capture Main()'s return value with the help of a batch file. Using the Windows
    Explorer, put MyFirstCSharpCode.bat intoC:DocumentsVisual Studio
        2010ProjectsMyFirstCSharpCode folder. The file looks like this:

                                      @echo off

                rem A batch file for MyFirstCSharpCode.exe
                rem which captures the app's return value.

                             MyFirstCSharpCode
                  @if "%ERROELEVEL%" == "0" goto success
:fail
                      echo This application has failed!
                      echo return value = %ERRORLEVEL%
                                   goto end
                                   :success
                    echo This application has succeeded!
                      echo return value = %ERRORLEVEL%
                                   goto end
                                     :end
                                 echo Done.

Let's open a command prompt and navigate to the folder containing our executable and
               the new batch file. Execute the batch file by typing in the
         name MyFirstCSharpCode.bat and pressing the Enter key. We'll get:

                                 My first C# code
                                   Hello World!

                                 Testing Error
                         This application has failed!
                               return value = -1
                                    Done..

   However, a vast majority of our C# application will use void as the return value
from Main(), which implicitly returns the error code of zero. We may not the batch file
                                         at all.



                          Command-Line Arguments

Let's look at the incoming array of string data. Now we want to update our application
         to process any possible command-line parameters using a C# for loop.

                               // Program4.cs
                                using System;
                      usingSystem.Collections.Generic;
                              usingSystem.Linq;
                              usingSystem.Text;

                        namespaceMyFirstCSharpCode
                                     {
                              class Program4
                                       {
                       staticint Main(string[] args)
                                         {
                  Console.WriteLine("My first C# code");
Console.WriteLine("Hello World!");
                            Console.WriteLine();
                      for(inti = 0; i<args.Length; i++)
                   Console.WriteLine("Arg: {0}", args[i]);
                             Console.ReadLine();
                                  return -1;
                                           }
                                         }
                                      }

  Here, we are checking to see whether the array of strings contains the number of
                 items using the Length property ofSystem.Array.

                                    C:>cd CSharp

                       C:CSharp>csc Program4.cs
       Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
       Copyright (C) Microsoft Corporation. All rights reserved.


                        C:CSharp>Program4 argAargBargC
                                My first C# code
                                  Hello World!

                                       Arg: argA
                                       Arg: argB
                                       Arg: argC

                                      C:CSharp>

  As we loop over each item in the array, its value is printed to the console window.

      We can use an alternative to the standard for loop. We may iterate over an
               incoming string array using the C# foreachkeyword:

                            foreach(string a in args)
                           Console.WriteLine("Arg: {0}", a);

             We are also able to access command-line argument using the
   static GetCommandLineArgs() method of theSystem.Environment type. The
return value of this method is an array of strings. The first index identifies the name of
 the application itself, while the remaining elements in the array contain the individual
                                 command-line arguments.

                                // Program5.cs
                                 using System;
                       usingSystem.Collections.Generic;
                               usingSystem.Linq;
usingSystem.Text;

                       namespaceMyFirstCSharpCode
                                    {
                             class Program5
                                      {
                      staticint Main(string[] args)
                                        {
                Console.WriteLine("My first C# code");
                   Console.WriteLine("Hello World!");
                          Console.WriteLine();
        string[] arguments = Environment.GetCommandLineArgs();
                    foreach(string arg in arguments)
                  Console.WriteLine("Arg: {0}", arg);
                           Console.ReadLine();
                               return -1;
                                        }
                                      }
                                    }

                                      Output is

                      C:CSharp>csc Program5.cs
      Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
      Copyright (C) Microsoft Corporation. All rights reserved.


                       C:CSharp>Program5 argAargBargC
                               My first C# code
                                 Hello World!

                                   Arg: Program5
                                     Arg: argA
                                     Arg: argB
                                     Arg: argC


                                     C:CSharp>


           Command-Line Arguments with Visual Studio 2010

While in the real world, the user supplies the command-line arguments, we may want
          to specify command-line argument during the development cycle.

To specify the arguments with Visual Studio 2010, double-click the Properties icon from
                                  Solution Explorer.
Then, select the Debug tab on the left side. After that we can specify values using the
                         Command line arguments text box.
List of C# Tutorials

       .NET Framework
Introduction - My First C# Code
  System Members and Data
            Modifiers
              Array
     Enumeration (Enums)
  Value and Reference Types
 Constructor and this Keyword
        static Keyword
     Encapsulation Services
          Inheritance
         Inheritance II
         Polymorphism
           Interfaces
           Delegates
        System.Object
             Events
Multi Threading I - Introduction and Simple Thread
             Multi Threading II - ThreadStart/ParameterizedThreadStart,
                          Foreground/Background Threads
                 Multi Threading III - Concurrency, Synchronization
                   Networking I - PORT, IPv4/IPv6, TCP/UDP, URI
              Networking II - WebRequest/WebResponse, WebClient




Home | About Us | products | Our Services | Contact Us | Bogotobogo © 2012 | Bogotobogo

More Related Content

What's hot

Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Xavier Hallade
 
The use of Symfony2 @ Overblog
The use of Symfony2 @ OverblogThe use of Symfony2 @ Overblog
The use of Symfony2 @ OverblogXavier Hausherr
 
Efficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverEfficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverShuo Chen
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.Richard Taylor
 
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)ZFConf Conference
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7Wim Godden
 
Muduo network library
Muduo network libraryMuduo network library
Muduo network libraryShuo Chen
 
Minko - Scripting 3D apps with Lua and C++
Minko - Scripting 3D apps with Lua and C++Minko - Scripting 3D apps with Lua and C++
Minko - Scripting 3D apps with Lua and C++Minko3D
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8Wim Godden
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance GainsVMware Tanzu
 

What's hot (20)

Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Java lab lecture 1
Java  lab  lecture 1Java  lab  lecture 1
Java lab lecture 1
 
The use of Symfony2 @ Overblog
The use of Symfony2 @ OverblogThe use of Symfony2 @ Overblog
The use of Symfony2 @ Overblog
 
Java lab zero lecture
Java  lab  zero lectureJava  lab  zero lecture
Java lab zero lecture
 
l-rubysocks-a4
l-rubysocks-a4l-rubysocks-a4
l-rubysocks-a4
 
Corejava ratan
Corejava ratanCorejava ratan
Corejava ratan
 
Android NDK
Android NDKAndroid NDK
Android NDK
 
Efficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverEfficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ server
 
Dvm
DvmDvm
Dvm
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.
 
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
ZFConf 2012: Dependency Management в PHP и Zend Framework 2 (Кирилл Чебунин)
 
Was faqs
Was faqsWas faqs
Was faqs
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
 
Muduo network library
Muduo network libraryMuduo network library
Muduo network library
 
Minko - Scripting 3D apps with Lua and C++
Minko - Scripting 3D apps with Lua and C++Minko - Scripting 3D apps with Lua and C++
Minko - Scripting 3D apps with Lua and C++
 
.Net slid
.Net slid.Net slid
.Net slid
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance Gains
 

Viewers also liked

Viewers also liked (7)

C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
C# basics
 C# basics C# basics
C# basics
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
 
Online Airline Ticket reservation System
Online Airline Ticket reservation SystemOnline Airline Ticket reservation System
Online Airline Ticket reservation System
 
Wedding project management
Wedding project managementWedding project management
Wedding project management
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 

Similar to C# tutorial

01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programmingmaznabili
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptxMugilvannan11
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkDr.Neeraj Kumar Pandey
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application DevelopmentRamesh Prasad
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersDave Bost
 
01. introduction to-programming
01. introduction to-programming01. introduction to-programming
01. introduction to-programmingStoian Kirov
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notesWE-IT TUTORIALS
 
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0Antonio Chagoury
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010Satish Verma
 
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
.Net framework
.Net framework.Net framework
.Net frameworkRaghu nath
 
01. Introduction to Programming
01. Introduction to Programming01. Introduction to Programming
01. Introduction to ProgrammingIntro C# Book
 

Similar to C# tutorial (20)

Srgoc dotnet_new
Srgoc dotnet_newSrgoc dotnet_new
Srgoc dotnet_new
 
01 Introduction to programming
01 Introduction to programming01 Introduction to programming
01 Introduction to programming
 
Introduction to Programming Lesson 01
Introduction to Programming Lesson 01Introduction to Programming Lesson 01
Introduction to Programming Lesson 01
 
Dotnet basics
Dotnet basicsDotnet basics
Dotnet basics
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net Framework
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
 
01. introduction to-programming
01. introduction to-programming01. introduction to-programming
01. introduction to-programming
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
 
Part i
Part iPart i
Part i
 
Dot net
Dot netDot net
Dot net
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0
A Sneak Peek At Visual Studio 2010 And .Net Framework 4.0
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
 
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
21UCAC61 C# and .Net Programming.pdf(MTNC)(BCA)
 
.Net framework
.Net framework.Net framework
.Net framework
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
01. Introduction to Programming
01. Introduction to Programming01. Introduction to Programming
01. Introduction to Programming
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
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
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
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
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

C# tutorial

  • 1. bogotobogo Bogotobogo contact@bogotobogo.com Home | Sitemap | Contact Us Home | About Us | Products | Our Services | Contact Us Gif |JavaApplet/Web Start | Flash | ShockWave | SVG | iPhone/iPad | Android | HTML5 |Algorithms | News | C++ | Java | PHP | Design Patterns | Python | C# | Forums Search Introduction List of C# 4.0 Tutorials .NET Framework Introduction - My First C# Code System Members and Data Modifiers Array
  • 2. Enumeration (Enums) Value and Reference Types Constructor and this Keyword static Keyword Encapsulation Services Inheritance Inheritance II Polymorphism Interfaces Delegates System.Object Events Multi Threading I - Introduction and Simple Thread Multi Threading II - ThreadStart/ParameterizedThreadStart, Foreground/Background Threads Multi Threading III - Concurrency, Synchronization Networking I - PORT, IPv4/IPv6, TCP/UDP, URI Networking II - WebRequest/WebResponse, WebClient Introduction C# is a multi-paradigm programming language encompassing imperative, declarative, functional, generic, object-oriented, and component-oriented programming disciplines. It was developed by Microsoft within the .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed for the Common Language Infrastructure (CLI). C# is intended to be a simple, modern, general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 4.0, which was released on April 12, 2010.
  • 3. What's new in C# 4.0 C# 4.0 is the latest version, which was released in April 11, 2010. Microsoft has released the 4.0 runtime and development environment Visual Studio 2010. The major focus of C# 4.0 is interoperability with partially or fully dynamically typed languages and frameworks, such as the Dynamic Language Runtime and COM. Your Ad Here Here are new features: Dynamic member lookup A new pseudo-type dynamic is introduced into the C# type system. It is treated as System.Object, but in addition, any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an operator on a value of such type is permitted without any type checking, and its resolution is postponed until run-time. This is known asDuck typing. Covariant and contravariant generic type parameters Generic interfaces and delegates can have their type parameters marked as covariant or contravariant, using keywords out and in, respectively. These declarations are then respected for type conversions, both implicit and explicit, and both compile-time and run-time. Optional ref Keyword when using COM The ref keyword for callers of methods is now optional when calling into methods supplied by COM interfaces. Optional parameters and named arguments C# 4.0 introduces optional parameters with default values as seen in Visual Basic and C++.
  • 4. Indexed properties Indexed properties (and default properties) of COM objects are now recognized, but C# objects still do not support them. Visual Studio Command Prompt You can invoke the C# compiler by typing the name of its executable file, csc.exe on the command line. If you use the Visual Studio Command Prompt (available as a shortcut on the start menu under Visual Studio Tools), all the necessary environment variables are set for you. Otherwise, you must adjust your path in order to enable csc.exe to be invoked from any subdirectory on your computer. If you do not use the Visual Studio Command Prompt, you must run vsvars32.bat under C:Program Files (x86)Microsoft Visual Studio 10.0Common7Tools to set the appropriate environment variables to support command line builds. Let's start with Visual Studio 2010: Start -> Programs -> Visual Studio 2010 -> Visual Studio Tools. Then, type in csc -? We get:
  • 5. If we want to make it work on other command prompt, we should set the new path. For my system the paths are: C:WindowsMicrosoft.NETFramework64v4.0.30319 C:Program Files (x86)Microsoft SDKsWindowsv7.0ABin C:Program Files (x86)Microsoft Visual Studio 10.0SDKv3.5Bin Once you have updated your Path variable, close all dialog boxes and any currently opened Console windows to commit the settings. You should now be able to execute csc.exe and other .NET tools from any Command prompt. To test, enter the following commands: csc -? ildasm -? We can check it's working if we see the same output as the one running from the Visual Studio Prompt. Simple Command Line C# Option Description This option is used to specify the name of the assembly to be created. By /out default, the assembly name is the same as the name of the initial input *.cs file. This option is used to specify the name of the assembly to be created. By /target:exe default, the assembly name is the same as the name of the initial input *.cs file. /target:library This option builds a single-file *.dll assembly /target:module This option builds a module. Modules are elements of multifile assemblies. Although we are free to build graphical user interface-based applications using /target:winexe the target:exe. Modules are elements of multifile assemblies. Compiles File.cs producing File.exe csc /target:exeFile.cs Compiles File.cs using abbreviation producing File.exe csc /t:exeFile.cs
  • 6. Compiles File.cs producing File.exe because /t:exe is the default output. cscFile.cs Compiles File.cs producing File.dll csc /target:libraryFile.cs Compiles File.cs and creates MyCSharp.exe: csc /out:MyCSharp.exe File.cs Compiles all the C# files in the current directory, with optimizations on and defines the DEBUG symbol. The output is File2.exe csc /define:DEBUG /optimize /out:File2.exe *.cs Compiles all the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs Compiles all the C# files in the current directory to Something.useful (a DLL): csc /target:library /out:Something.useful *.cs C# Compiler vs. C++ Compiler There are no object (.obj) files created as a result of invoking the C# compiler; output files are created directly. As a result of this, the C# compiler does Not need a linker My First C# Program Here is our first C# code:
  • 7. // Program.cs using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceMyFirstCSharpCode { class Program { static void Main(string[] args) { } } } A C# program consists of one or more type declarations. C# requires that all program be contained within a type (class, interface, structure, enumeration, delegate etc.) definition. In other words, all data members and methods must be contained within a type definition. In the above example, only the class type is declared. The code is created as a new Console Application project named MyFirstCSharpCode. The program uses two namespaces. It creates a new namespace called MyFirstCSharpCode, and uses a predefined namespace called System. The method Main() is a member of class MyFirstCSharpCode and it's a special function used by the compiler as the starting point of the program. By default, Visual Studio names the class defining Main(). Here, it's the Program. So, the file name isProgram.cs. However, we are free to change this if we so choose. The class that defines the Main() method is termed the application object (which can be useful when performing unit tests), we must inform the compiler which Main() method should be used as the entry point via the /main option of the command-line compiler. Note that the signature of Main() is adorned with the static keyword. Static members are scoped to the class level rather than the object level and can thus be invoked without the need to first create a new class instance. In addition to the static keyword, this Main() method has a single parameter, which is an array of strings: string[] args
  • 8. To compile the program, we can use Visual Studio or the command-line compiler. To use the command-line compiler, use the following command: cscProgram.cs In this command, csc is the name of the command-line compiler and Program.cs is the name of the source file. Let's make the code more interesting: // Program2.cs using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceMyFirstCSharpCode { class Program2 { static void Main(string[] args) { Console.WriteLine("My first C# code"); Console.WriteLine("Hello World"); Console.WriteLine(); Console.ReadLine(); } } } In the new code, we make use of the Console class, which is defined within the System namespace. Among its set of members is the static WriteLine() which pumps a text string and carriage return to the standard output. We also make a call toConsole.ReadLine() to ensure the command prompt launched by the Visual Studio 2010 IDE remains visible during a debugging session until we press the Enter key. Note that we have several methods for our Main(): static int Main(string[] args) static void Main() static int Main() Error Code
  • 9. The ability to return an int from Main() keeps C# consistent with other C-based languages. By convention, returning the value 0indicates the program has terminated successfully, while another value such as -1 represents an error condition. On the Windows OS, an application's return value is stored within a system environment variable named %ERRORLEVEL%. If we were to create an application that programmatically launches another executable, we can obtain the value of%ERRORLEVEL% using the static System.Diagnostics.Process.ExitCode property. Given that an application's return value is passed to the system at the time the application terminates, it is obviously not possible for an application to obtain and display its final error code while running. However, to illustrate how to view this error level upon program termination, begin by updating the Main() method: // Program3.cs using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceMyFirstCSharpCode { class Program3 { staticint Main(string[] args) { Console.WriteLine("My first C# code"); Console.WriteLine("Hello World!"); Console.WriteLine(); Console.ReadLine(); return -1; } } } Let's capture Main()'s return value with the help of a batch file. Using the Windows Explorer, put MyFirstCSharpCode.bat intoC:DocumentsVisual Studio 2010ProjectsMyFirstCSharpCode folder. The file looks like this: @echo off rem A batch file for MyFirstCSharpCode.exe rem which captures the app's return value. MyFirstCSharpCode @if "%ERROELEVEL%" == "0" goto success
  • 10. :fail echo This application has failed! echo return value = %ERRORLEVEL% goto end :success echo This application has succeeded! echo return value = %ERRORLEVEL% goto end :end echo Done. Let's open a command prompt and navigate to the folder containing our executable and the new batch file. Execute the batch file by typing in the name MyFirstCSharpCode.bat and pressing the Enter key. We'll get: My first C# code Hello World! Testing Error This application has failed! return value = -1 Done.. However, a vast majority of our C# application will use void as the return value from Main(), which implicitly returns the error code of zero. We may not the batch file at all. Command-Line Arguments Let's look at the incoming array of string data. Now we want to update our application to process any possible command-line parameters using a C# for loop. // Program4.cs using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceMyFirstCSharpCode { class Program4 { staticint Main(string[] args) { Console.WriteLine("My first C# code");
  • 11. Console.WriteLine("Hello World!"); Console.WriteLine(); for(inti = 0; i<args.Length; i++) Console.WriteLine("Arg: {0}", args[i]); Console.ReadLine(); return -1; } } } Here, we are checking to see whether the array of strings contains the number of items using the Length property ofSystem.Array. C:>cd CSharp C:CSharp>csc Program4.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. C:CSharp>Program4 argAargBargC My first C# code Hello World! Arg: argA Arg: argB Arg: argC C:CSharp> As we loop over each item in the array, its value is printed to the console window. We can use an alternative to the standard for loop. We may iterate over an incoming string array using the C# foreachkeyword: foreach(string a in args) Console.WriteLine("Arg: {0}", a); We are also able to access command-line argument using the static GetCommandLineArgs() method of theSystem.Environment type. The return value of this method is an array of strings. The first index identifies the name of the application itself, while the remaining elements in the array contain the individual command-line arguments. // Program5.cs using System; usingSystem.Collections.Generic; usingSystem.Linq;
  • 12. usingSystem.Text; namespaceMyFirstCSharpCode { class Program5 { staticint Main(string[] args) { Console.WriteLine("My first C# code"); Console.WriteLine("Hello World!"); Console.WriteLine(); string[] arguments = Environment.GetCommandLineArgs(); foreach(string arg in arguments) Console.WriteLine("Arg: {0}", arg); Console.ReadLine(); return -1; } } } Output is C:CSharp>csc Program5.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. C:CSharp>Program5 argAargBargC My first C# code Hello World! Arg: Program5 Arg: argA Arg: argB Arg: argC C:CSharp> Command-Line Arguments with Visual Studio 2010 While in the real world, the user supplies the command-line arguments, we may want to specify command-line argument during the development cycle. To specify the arguments with Visual Studio 2010, double-click the Properties icon from Solution Explorer.
  • 13. Then, select the Debug tab on the left side. After that we can specify values using the Command line arguments text box.
  • 14. List of C# Tutorials .NET Framework Introduction - My First C# Code System Members and Data Modifiers Array Enumeration (Enums) Value and Reference Types Constructor and this Keyword static Keyword Encapsulation Services Inheritance Inheritance II Polymorphism Interfaces Delegates System.Object Events
  • 15. Multi Threading I - Introduction and Simple Thread Multi Threading II - ThreadStart/ParameterizedThreadStart, Foreground/Background Threads Multi Threading III - Concurrency, Synchronization Networking I - PORT, IPv4/IPv6, TCP/UDP, URI Networking II - WebRequest/WebResponse, WebClient Home | About Us | products | Our Services | Contact Us | Bogotobogo © 2012 | Bogotobogo