540 likes | 572 Views
Introduction to Web Application. Introduction to C#. Topics. C# Basics The type system Components. C#.
E N D
Introduction to Web Application Introduction to C#
Topics • C# Basics • The type system • Components
C# C# is a simple, modern, object oriented, and type-safeprogramming language derived from C and C++. It will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++. Anders Hejlsberg Chief Designer of C#, Turbo Pascal, Delphi and Visual J++
Hello World Namespace directive Provided by the Microsoft .NET Framework class library using System; class Hello { static void Main() { Console.WriteLine("Hello world"); } } The main entry point for a program Console.WriteLine is a shorthand for System.Console.WriteLine. public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello world”); } }
Run the application • csc h.cs • h.exe • javac HelloWorld.java • java HelloWorld
C# Program Structure package • Namespaces • Contain types and other namespaces • Type declarations • Classes, structs, interfaces, enums, and delegates • Members • Constants, fields, methods, operators, constructors, destructors • Properties, indexers, events • Organization • No header files, code written “in-line” • No declaration order dependence class
C# Program Structure using System; namespace System.Collections { public class Stack { Entry top; public void Push(object data) { top = new Entry(top, data); } public object Pop() { if (null == top) throw new InvalidOperationException(); object result = top.data; top = top.next; return result; } } }
Overview of Common Type System • CTS supports both value and reference types Type Value Type Reference Type
Declaring and Releasing Reference Variable Coordinate c1; c1 = new Coordinate(); c1.x = 6.12; c1.y = 4.2; • Declaring and assigning reference variables • 6.12 4.2 • Releasing reference variables c1 = null; • 6.12 4.2
Comparing Value Types to Reference Types • Reference types • The variable contains a reference to the data • Data is stored in a separate memory area • Value types • The variable contains the value directly • Examples: char, int string s; s = "Hello"; int i; i = 42; • Hello 42
123 i "Hello world" s Reference and Value Types 123 j t int i = 123; string s = "Hello world"; int j = i; string t = s;
class T sbyte decimal bool byte char ushort short uint float int ulong double long C# Type System String Array T[ ] Object Enum enum T ValueType struct T
Predefined Types • C# predefined types • Reference object, string • Signed sbyte, short, int, long • Unsigned byte, ushort, uint, ulong • Floating-point float, double, decimal • Character char • Logical bool • Predefined types are simply aliases for system-provided types • For example, int == System.Int32
Question using System; class Test { static void Main() { string s = "Test"; string t = string.Copy(s); Console.WriteLine(s == t); Console.WriteLine((object)s == (object)t); } }
Unifying the Type System • Unifyreference and value types • A single universal basetype • Can hold any value • Unification enables: • Calling virtual functions on any value • Collection classes for any type • No wrapper classes • Replacing OLE Automation Variant type
How to Unify: C# Approach • All value types are derived from the ultimate base type “object”. • Value types automatically become reference types when necessary. • Heap allocation only when needed • Objects remain strongly typed. • Process is known as “boxing”
Boxing and Unboxing • Boxing and Unboxing can make an instance to encapsulate a value-typedvariable, and use it as reference type
Boxing and unboxing using System; class test{ staticvoid Main(){ int i=123; object o = i; //boxing int j = (int) o; //unboxing } }
Boxing using System; class test{ staticvoid Main(){ int i=123; object o = i; //boxing int j = (int) o; //unboxing } } i 123 int i = 123 Boxing i o ref int 123 object o = i
Unboxing i 123 int i = 123 Boxing i o int 123 ref object o = i j 123 int j = (int)o Unboxing o
User-Defined Types • Classes (reference) • Used for most objects • Structs (value) • Objects that are like data (Point, Complex, etc). • Interfaces
CAR? What Is a Class? • For the philosopher… • An artifact of human classification! • Classify based on common behavior or attributes • Agree on descriptions and names of useful classes • Create vocabulary; we communicate; we think! • For the object-oriented programmer… • A named syntactic construct that describes common behavior and attributes • A data structure that includes both data and functions
What Is an Object? • An object is an instance of a class • Objects exhibit: • Identity: Objects are distinguishable from one another • Behavior: Objects can perform tasks • State: Objects store information
Classes • Single inheritance • Multiple interface implementation • Class members • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors • Static and instance members • Nested types • Member access • Public, protected, internal, protect internal, private
Member accessibility • private • Accessible only by methods in the defining type • protected • Accessible only by methods in this type or one of its derived types without regard to assembly • internal • Accessible only by methods in the defining assembly • protectinternal • Accessible only by methods in this type any derived type, or any type defined in the defining assembly • public • Accessible to all methods in all assemblies
Creating Objects • Step 1: Allocating memory • Use new keyword to allocate memory from the heap • Step 2: Initializing the object by using a constructor • Use the name of the class followed by parentheses Date when = new Date( );
Object Cleanup • The final actions of different objects will be different • Those actions cannot be determined by garbage collection • Objects in .NET Framework have a Finalize method • If present, garbage collection will call destructor before reclaiming the raw memory • In C#, implement a destructor to write cleanup code • You cannot call or override Object.Finalizein C#
Structs • Same as classes, but “value” behavior • Allocated inline • Always have a value • Assignment copies data • Inheritance? • Can’t derive from other types • Can’t be derived from • Advantages • Behave like a piece of data • Light weight • No heap allocation, less GC pressure
Class vs Struct class Point{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; }} struct Point{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; }} Point a = new Point(10, 10); Point b = a; a.x = 20; Console.WriteLine(b.x);
Interfaces • Can contain methods, properties, indexers, and events interface IDataBound { void Bind(IDataBinder binder); } class EditBox: Control, IDataBound { void Bind(IDataBinder binder) {...} }
Component Development • What defines a component? • Properties, methods, events • Integrated help and documentation • Design-time information • C# has first class support • Components are easy to build and consume • Can be embedded (ASP.net pages)
Properties • Properties are “smart fields” • Natural syntax, accessors, inlining public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } } } Button b = new Button(); b.Caption = "OK"; String s = b.Caption;
Creating a Simple .NET Framework Component with C# • Using Namespaces and Declaring the Class • Creating the Class Implementation • Implementing Structured Exception Handling • Creating a Property • Compiling the Component
Using Namespaces and Declaring the Class • Create a New Namespace • Declare the Class using System; namespace CompCS {...} public class StringComponent {...}
Creating the Class Implementation private string[] stringSet; • Declare a Private Field of Type Array of String Elements • Create a Public Default Constructor • Assign the stringSet Field to an Array of Strings public StringComponent() {...} stringSet = new string[] { "C# String 0", "C# String 1", ... };
Implementing Structured Exception Handling public string GetString(int index) {...} • Implement the GetString Method • Create and Throw a New Object of Type IndexOutOfRangeException • Exceptions Caught by the Caller Using a try/catch/finally Statement • Structured Exception Handling Replaces HRESULT-Based Error Handling in COM if((index < 0) || (index >= stringSet.Length)) { throw new IndexOutOfRangeException(); } return stringSet[index];
Creating a Property • Create a Read-Only Count Property to Get the Number of String Elements in the stringSet Array public int Count { get { return stringSet.Length; } }
Compiling the Component • Use the /target:library Switch to Create a DLL • Otherwise, an executable with a .dll file extension is created instead of a DLL library csc /out:CompCS.dll /target:library CompCS.cs
Creating a Simple Console Client • Using the Libraries • Instantiating the Component • Calling the Component • Building the Client
Using the Libraries • Reference Types Without Having to Fully Qualify the Type Name • If Multiple Namespaces Contain the Same Type Name, Create a Namespace Alias to Remove Ambiguity using CompCS; using CompVB; using CSStringComp = CompCS.StringComponent; using VBStringComp = CompVB.StringComponent;
Instantiating the Component • Declare a Local Variable of Type StringComponent • Create a New Instance of the StringComponent Class //… using CSStringComp = CompCS.StringComponent; //… CSStringComp myCSStringComp = new CSStringComp();
Calling the Component • Iterate over All the Members of StringComponent and Output the Strings to the Console for (int index = 0; index < myCSStringComp.Count; index++) { Console.WriteLine (myCSStringComp.GetString(index)); }
Building the Client • Use the /reference Switch to Reference the Assemblies That Contain the StringComponent Class csc /reference:CompCS.dll /out:ClientCS.exe ClientCS.cs
Creating an ASP.NET Client • Writing the HTML for the ASP.NET Application • Coding the Page_Load Event Handler • Generating the HTML Response
Writing the HTML for the ASP.NET Application <%@ Page Language="C#" Description="ASP.NET Client" %> • Specify Page-Specific Attributes Within a Page Directive • Import the Namespace and the Physical Assembly • Specify Code Declaration Blocks <%@ Import Namespace="CompCS"%> <script language="C#" runat=server> ... </script>
Coding the Page_Load Event Handler void Page_Load(Object sender, EventArgs EvArgs) { StringBuilder Out = new StringBuilder(""); int Count = 0; // Iterate over component's strings and concatenate Out.Append("Strings from C# Component<br>"); CompCS.StringComponent myCSStringComp = new CompCS.StringComponent(); for(int index = 0; index < myCSStringComp.Count; index++) { Out.Append(myCSStringComp.GetString(index)); Out.Append("<br>"); } // … Message.InnerHtml = Out.ToString(); }
Generating the HTML Response • Specify the Body of the HTML Response <body> <span id="Message" runat=server/> </body>
System.String • Look up MSDN!