Csharp by hmoda


									   C# - The Language of DotNet

                 An Introduction to C#

MSc E-Commerce
             Languages for DotNet
• DotNet can be programmed in many different
    – Microsoft – Visual Basic, C++, JavaScript, C#
    – 20 languages from other suppliers
    – Class written in one language can be extended in another
• Languages have to be adapted to fit with DotNet
  and the Common Language Runtime
    –   Much of the functionality is in the CLR
    –   Much of the programming is the same in any language as a result
    –   Must support Single Inheritance, Interfaces etc
    –   Must be written for DotNet standard not original standard of the language
    –   Multiple Inheritance lost from C++.net
    –   DotNet has a Common Type System
MSc E-Commerce
        Languages and ASP.NET
• 2 main languages for ASP.NET
    – Visual Basic.net and C#
    – Cannot use C++ for ASP.NET
• VB.NET likely to a popular language for dotnet,
  because many programmers familiar with VB,
  BUT VB.NET has been changed a great deal, it is
  almost a new language
• C# is a new language and then one used to write
  the DotNet itself

MSc E-Commerce
                        What is C#
• A modern language in the C family
    – Basic syntax is similar to C and C++
        • Case sensitive, semi-colons, braces etc
    – Fully Object-Orientated – closest relative is Java
        • Has Garbage Collection like Java
        • But slightly closer to C++ than Java is
    – Not identical to Java
        • Has ideas from Delphi and VB as well
        • Pointers can be used in some circumstances
        • Use Pascal not Camel Casing, e.g. ToString not toString()

MSc E-Commerce
                 Better than Java?
• Has Properties, Events, Delegates as part of
• Has an extra loop - for each
• Switch statement – “safer” and more flexible than
  in C and Java
• Value data types are better
    – Can pass by reference
    – Can create own value “classes” called struts
    – Boxing of basic data type to reference ones
        • So this works – 231.ToString(); where 231 is a literal number
• Has assert
MSc E-Commerce
                 Worse Than Java?
• Arguments For and Against these
    – Operator Overloading, can define + etc for own class
    – Method Overriding and Inheritance
        • In Java can override unless author of parent prevents you
        • In C# (and C++) can’t override unless author of parent
          explicitly lets you
        • In C# override keyword required for overridden method
    – Exceptions - has try catch finally like Java, but don’t
      have to be handled
        • Most Java advocates think this is a mistake but this one does
        • Java and Checked Exceptions by Bruce Eckel
MSc E-Commerce
       Java Packages and Classes
• In a Java Class source
    – Only 1 public class allowed
    – The name of the file must be the name of the public
• In the Package “structure” e.g.
    – com.essex.rjw.mybeans
    – com, essex, rjw, mybeans refers to a directory structure
• In C# Namespaces are roughly equivalent to
  packages, but they are not the same
MSc E-Commerce
       C# - Class and Namespace
• You can have 1 or more classes in the same file
• The name of the file does not have to be the same
  as any of the classes
• File extension for C# source file is .cs
• All classes are part of a namespace
    – If you leave out the namespace the class becomes part
      of the global namespace
    – Namespaces can be left out for simple programs
    – Namespaces have no connection with any directory
MSc E-Commerce
           Example in C# and Java
•   using System;                        • package mystuff;
•   namespace VeryBasicCSharp            • import java.lang;
•   {                                    • class VeryBasicJava
•          class SharpFirst
                                         •        {
•          {
                                         •          static void main(String[]
•            static void Main(String[]
                                           args )
    args )
•             {                          •           {
•             Console.WriteLine("This    •
    is C sharp");                          System.out.println("This is
•             return;                      Java");
•             }                          •           return;
•          }                             •           }
•   }                                    •        }
MSc E-Commerce
• Using similar to import in Java
• Namespace encloses any classes between {
  and }
• Main method starts with capital M
• Classes often have different names but
  Console is similar to System in Java
• Methods often have different names but
  many are similar
MSc E-Commerce
                  Compiling C#
• Compiler is called csc.exe
• To compile hand written C# program
    – Open Command Window
    – Put csc.exe on the Path (all one line)
        • set
    – Move to directory containing source code
    – Run the compiler
        • csc MyProgram.cs
• Visual Studio will compile and run program for you
• There is no equivalent to CLASSPATH in C#
MSc E-Commerce
                 ASP.NET Programs
• Like JSP Pages you don’t need to pre-
  compile ASP.NET applications
    – Either
        • Start Browser and type in address of desired page
    – Or
        • With a Visual Studio project –select
        • Start Without Debugging from Debug Menu
        • You can’t “Debug” ASP.NET programs in our Labs
          due to permissions

MSc E-Commerce
                  Data Types in C#
• As in Java there are Value and Reference data
• Value – (primitive data types)
    – Integer types –
        • byte, sbyte (1 byte)
        • short (2 bytes), int (4), long (8)
        • ushort, uint, ulong (unsigned ones)
    – Floating point types
        • float (7 sig fig), double (15/16),
        • decimal (28 sig fig) (for currency)
    – Others
         • bool
         • char
MSc E-Commerce
                 Arrays in C Sharp
• The array declaration is a little different to
  that in C
    –C       float fArray[] = new float[100];
    – C#     float[] fArray = new float[100];
    – Single, Multi-dimensional and Jagged
    – Can use the foreach syntax to get at all
      elements in the array
    – Notes and Example
MSc E-Commerce
         C# types and CTS Types
• All basic data types have an equivalent struct
  object in the CTS e.g.
    – int is the same as System.Int32
    – structs are a value type class object
    – Can have methods etc, like classes but with some restrictions, e.g. non
    – Basic data types and CTS structs are pretty interchangeable
    – This works in C#
         • int x = 24;
         • string str = x.ToString();
    – So does this where 24 is a literal value
         • 24.ToString();

MSc E-Commerce
                 Reference Types
• string (CTS = System.String)
    – Similar to String in Java e.g. its value “cannot”
      be changed i.e. if change value of string it
      makes a new string
    – For dynamic strings use StringBuilder class
      similar to StringBuffer in Java
• object (CTS = System.Object) root type of
  all types in CTS (including value ones)
MSc E-Commerce
                 Class Objects
• Structs and other value types created on the
• Reference Types created on the heap
• Created by new (as in Java)
    – Also true for struct objects!
• Classes similar to Java
    – single inheritance only
    – Can implement one or more interfaces
MSc E-Commerce
          Class Syntax – Properties
•   class MyParent                          • Setting property value
•   {
•         protected string firstname;          – MyParent dad = new
•         public string FirstName                MyParent();
•         {          get
                                               – dad.FirstName = "sid";
•                    {
•                     return firstname;     • Getting property value
•                    set                       – string who =
•                    {                           dad.FirstName;
•                      firstname = value;
•                    }
•         }
•   }

MSc E-Commerce
•   Single inheritance only allowed
•   Syntax is C++ style
•   extends in Java, : in C#
•   Example code for inheritance
    – class MyChild : MyParent
• Simple Example and Notes

MSc E-Commerce
      Overriding Virtual Methods
• In a class hierarchy if base class has virtual
  method and child classes have override of it, then
  a reference to base class will call the method of
  the particular child class
• Method in “parent” must be declared as virtual
• Method in “child” class must use keyword
• Different way round to Java
• Notes and Example

MSc E-Commerce
Constructors and Deconstructors
• Constructors are the same as in Java
    – Can be overloaded
• Destructors – syntax, same as in C++
    – class MyClass {
    – public ~MyClass()
• Cannot know when (or even if) the Garbage
  Collector will remove object and therefore call
  destructor. (Same as in Java)
• Result – resources may not be released

MSc E-Commerce
             IDisposable Interface
• Classes which implement this interface
  must supply a Dispose method
• This method can be called by users of the
  class to clean up resources
• Need to supply code to release resources
• It is not called automatically
• Up to programmer to call it
MSc E-Commerce
• A class in C# can implement several
• Implementing an interface forces the class
  to have certain methods
• Part of the “Contract” idea
• Similar to Interfaces in Java
• Notes, Syntax and Example
MSc E-Commerce
• You have already come across them
    – Response.Form[“txtOne”]
    – Note: the square brackets
• Allows a class object to be treated like an
• Must contain data that can be treated like an
• Example and Notes
MSc E-Commerce
                 Switch and Case
• Similar syntax to C, C++ and Java
• Except
    – Test variable can be “integer” or string
    – Can’t “fall through” to next case
• Example and Notes

MSc E-Commerce
                 Exceptions in C#
• try, catch, finally and throws
• Similar to Java in most respects
• But
    – There are no Checked Exceptions in C# - a
      controversial decision
    – You cannot add throws ???Exception to method
• Example and Notes
MSc E-Commerce
• C# is a Java style OO language
• At least as good as Java
• Has some differences
• Uses a different set libraries to Java
• Like Java can be used for many different
  kinds of applications
• Can be used for coding ASP.NET
MSc E-Commerce

To top