580 likes | 748 Views
C#/.NET. Basics. .NET. Runtime environment called the Common Language Runtime (CLR) Class library called the Framework Class Library (FCL). Common Language Runtime. Modern runtime environment .NET compilers do not target a specific processor The CLR must be present on the target machine
E N D
C#/.NET Basics Carnegie Mellon University MSCF
.NET • Runtime environment called the Common Language Runtime (CLR) • Class library called the Framework Class Library (FCL) Carnegie Mellon University MSCF
Common Language Runtime • Modern runtime environment • .NET compilers do not target a specific processor • The CLR must be present on the target machine • Safely manages code execution • JIT compilation from MSIL to machine executable • Security and Permission management Carnegie Mellon University MSCF
Framework Class Library • Object oriented • Collections, console, network and file I/O • Database and XML support • Rich server side event model • Rich client side support for GUI construction • Support for building SOAP based web services • More than 3,500 classes Carnegie Mellon University MSCF
C# Overview • C# is type safe (hard to access objects in inappropriate ways) • Automatic memory management • Exception handling • Array bounds checking • Support for checked arithmetic Carnegie Mellon University MSCF
Hello World 1 Full Namespaces // Hello World 1 in C# class MyApp { public static void Main() { System.String x = "World"; System.Console.WriteLine("Hello " + x); } } MSCorLib.dll is one among many assemblies we can include. The Basic Class Library is spread over a couple of assemblies. The .exe file has bootstrap code to run the .NET run time. MyApp is in the global namespace Compile with csc -t:exe -out:HelloUser.exe -r:MSCorLib.dll HelloUser.cs Execute MSIL Managed Code with HelloUser The code runs within the Common Language Runtime (CLR) Carnegie Mellon University MSCF
Hello World 2 Using System // Hello World 2 in C# using System; class MyApp { public static void Main() { String x = "World 2"; Console.WriteLine("Hello " + x); } } Compile With csc HelloUser.cs Execute The MS Intermediate Language .exe file with HelloUser Carnegie Mellon University MSCF
Hello World 3 Without System // Hello World 3 in C# class MyApp { public static void Main() { String x = "World 3"; Console.WriteLine("Hello " + x); } } HelloUser.cs(9,7): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?) And more errors… Carnegie Mellon University MSCF
Code May Come From A Network • Has it been tampered with? • Who wrote it? • What permissions does it require? • What permissions should we grant it? • A major advantage of .NET over traditional Windows applications is fined-grained control over security. Carnegie Mellon University MSCF
Signing Hello World 4 (1) My Path Variable: C:\WINDOWS\system32; C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705; C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin • Generate 128-byte public/private key pair and place in a file • sn.exe –k PublicPrivate.snk • (2) Add an attribute to the source so that the compiler places the public • key in the executable, generates a hash and signs it. • (3) Signature verification is automatic but may be done manually with - • sn.exe -v MyApp.exe • (4) Verification is done against the public key in the executable and • not against the public key in PublicPrivate.snk Carnegie Mellon University MSCF
Signing Hello World 4 (2) // Hello World 4 in C# (with a signature) using System.Reflection; // Tell the compiler where the public/private key pair reside [assembly:AssemblyKeyFile("PublicPrivate.snk")] class MyApp { public static void Main() { System.String x = "World"; System.Console.WriteLine("Hello " + x); } } Carnegie Mellon University MSCF
Signing Hello World 4 (3) Create the keys D:\McCarthy\www\46-690\SignAnAssembly>sn.exe -k PublicPrivate.snk Key pair written to PublicPrivate.snk Compile code D:\McCarthy\www\46-690\SignAnAssembly>csc MyApp.cs Verification is automatic but here we force it D:\McCarthy\www\46-690\SignAnAssembly>sn.exe -v MyApp.exe Assembly 'MyApp.exe' is valid Carnegie Mellon University MSCF
Type System Unification 0 • The object class is the ultimate base class for both reference types and value types • Simple types in C# alias structs found in System • So, Simple types have methods int i = 3; string s = i.ToString(); • But follow the same semantics as simple types of old, e.g., i = 3; j = i; j = 2; // i still 3 Carnegie Mellon University MSCF
Type System Unification 1 class MyMathApp { public static void Main() { float x = 2.3F; // Semantics are the same System.Single y = 1.0F; // Only the syntax differs float z = x + y; System.Console.WriteLine("Result = " + z); } } Carnegie Mellon University MSCF
Type System Unification 2 // All types derive from System.Object (which corresponds to the primitive object // type.) class MyMathApp { public static void Main() { float x = 2.3F; // 2.3 is a double so use 'F' for float System.Single y = 1.0F; float z = x + y; object o = z; // object is part of C#, Object is in System System.Console.WriteLine("Object Result = " + o); } } Object Result = 3.3 Carnegie Mellon University MSCF
Exception Handling (1) // Exception Handling - loops forever using System; class CatchExceptionExample { public static void Main() { int result = 1; try { while(true) { result = result * 2; } } catch(Exception e) { Console.WriteLine("Exception caught"); Console.WriteLine(e.Message); } Console.WriteLine("Graceful termination"); } } Carnegie Mellon University MSCF
Exception Handling (2) // Exception Handling - Graceful termination using System; class CatchExceptionExample { public static void Main() { int result = 1; try { while(true) { result = checked(result * 2); } } catch(Exception e) { Console.WriteLine("Exception caught"); Console.WriteLine(e.Message); } Console.WriteLine("Graceful termination"); } } Carnegie Mellon University MSCF
Exception Handling (3) D:>CatchExceptionExample.exe Exception caught Arithmetic operation resulted in an overflow. Graceful termination Carnegie Mellon University MSCF
Parameters1 Pass By Value // C# Parameters using System; public class Parameter1 { static void inc(int x) { ++x; } public static void Main() { int a = 30; inc(a); Console.WriteLine(a); // 30 is displayed } } Carnegie Mellon University MSCF
Parameters 2 Pass by Reference // C# Parameters 2 using System; public class Parameter2 { static void inc(ref int x) { ++x; } public static void Main() { int a = 30; inc(ref a); Console.WriteLine(a); // 31 is displayed } } Carnegie Mellon University MSCF
Parameters 3 Passing Objects // C# Parameters using System; public class Student { public int age; } public class Parameter3 { static void swap(Student x, Student y) { Student t = x; x = y; y = t; } Carnegie Mellon University MSCF
public static void Main() { Student a = new Student(); a.age = 34; Student b = new Student(); b.age = 65; swap(a,b); Console.WriteLine(a.age +" " +b.age); // 34 65 } } Carnegie Mellon University MSCF
Parameter 4 Passing Objects // C# Parameters using System; public class Student { public int age; } public class Parameter4 { static void swap(ref Student x, ref Student y) { Student t = x; x = y; y = t; } Carnegie Mellon University MSCF
public static void Main() { Student a = new Student(); a.age = 34; Student b = new Student(); b.age = 65; swap(ref a,ref b); Console.WriteLine(a.age +" " +b.age); // 65 34 } } Carnegie Mellon University MSCF
Parameters 5 Out Parameters // C# Parameters using System; public class Student { public int age; } public class Parameter5 { static void MakeAStudent(out Student x) { x = new Student(); // assignment is required } Carnegie Mellon University MSCF
public static void Main() { Student a; MakeAStudent(out a); a.age = 34; Console.WriteLine(a.age); // 35 is displayed } } Carnegie Mellon University MSCF
Parameter 6 Passing Arrays // C# Parameters using System; public class Parameter6 { static decimal Multiply(params decimal[] a) { decimal amt = 0.0m; foreach(decimal i in a) amt += i; return amt; } Carnegie Mellon University MSCF
public static void Main() { decimal[] x = { 2.0m, 3.0m, 1.0m }; Console.WriteLine(Multiply(x)); // 6.0 is displayed } } Carnegie Mellon University MSCF
Classes 1 // Classes may have members with protection levels // The default is private. class Student { public string name; int age; public Student(string n, int a) { name = n; age = a; } } class MyClassApp { public static void Main() { Student s = new Student("Mike",23); System.Console.WriteLine("Student " + s.name); // illegal to try to display the age from here } } Carnegie Mellon University MSCF
Classes 2 internal class Student { public string name; int age; public Student(string n, int a) { // Classes default to 'internal' visibility. name = n; // MyClassApp is public and therefore age = a; // visible to external // assemblies. } } public class MyClassApp { public static void Main() { Student s = new Student("Mike",23); System.Console.WriteLine("Student " + s); } } Student Student Carnegie Mellon University MSCF
Classes 3 Properties using System; class Student { private string name; private int age; public String StudentName { set { name = value; } get { return name; } } Carnegie Mellon University MSCF
public int StudentAge { set { age = value; } get { return age; } } } public class MyClassApp { public static void Main() { Student s = new Student(); s.StudentName = "Mike"; // calls set s.StudentAge = 23; // calls set // call get Console.WriteLine(s.StudentName + ":" + s.StudentAge); } } Mike:23 Carnegie Mellon University MSCF
Classes 4 Inheritance // C# Classes and Inheritance using System; class Student { private string name; private int age; public String StudentName { set { name = value; } get { return name; } } Carnegie Mellon University MSCF
public int StudentAge { set { age = value; } get { return age; } } } Carnegie Mellon University MSCF
class GradStudent : Student { private String underGraduateDegree; public String Degree { set { underGraduateDegree = value; } get { return underGraduateDegree; } } } Carnegie Mellon University MSCF
public class DemoInheritance { public static void Main() { GradStudent s = new GradStudent(); s.StudentName = "Mike"; s.StudentAge = 23; s.Degree = "Philosophy"; Console.WriteLine(s.StudentName + ":" + s.StudentAge + ":" + s.Degree); } } Mike:23:Philosophy Carnegie Mellon University MSCF
Classes 5 Polymorphism // C# Classes and Polymorphism using System; public class Student { private string name; private int age; public String StudentName { set { name = value; } get { return name; } } Carnegie Mellon University MSCF
public int StudentAge { set { age = value; } get { return age; } } } Carnegie Mellon University MSCF
public class GradStudent : Student { private String underGraduateDegree; public String Degree { set { underGraduateDegree = value; } get { return underGraduateDegree; } } } Carnegie Mellon University MSCF
public class DoctoralStudent : GradStudent { private String thesisTitle; public String ThesisTitle { get { return thesisTitle; } } public DoctoralStudent(string thesis) { thesisTitle = thesis; } } Carnegie Mellon University MSCF
public class DemoInheritance { public static void Main() { GradStudent s = new GradStudent(); DoctoralStudent d = new DoctoralStudent("The Semantic Web"); s.StudentName = "Mike"; s.StudentAge = 23; d.StudentName = "Sue"; d.StudentAge = 25; Console.WriteLine(s.StudentName + ":" + s.StudentAge); Console.WriteLine(d.StudentName + ":" + d.StudentAge); Display(s); Display(d); } public static void Display(Student x) { // Method takes any Student Console.WriteLine(x.StudentName + ":" + x.StudentAge); } } Carnegie Mellon University MSCF
Type Constructors 1 // Classes may have "Type Constructors" internal class Student { public static int numberOfStudentsCreated; static Student() { // must take no args numberOfStudentsCreated = 0; } public string name; int age; public Student(string n, int a) { name = n; age = a; numberOfStudentsCreated++; } } Carnegie Mellon University MSCF
public class MyClassApp { public static void Main() { Student s = new Student("Mike",23); Student t = new Student("Sue",23); System.Console.WriteLine("Student's created = " + Student.numberOfStudentsCreated); } } HelloUser Student's created = 2 Carnegie Mellon University MSCF
GUI Programming (1) using System; using System.Windows.Forms; public class WindowGreeting { private String m_userName; public String UserName { set { m_userName = value; } get { return m_userName; } } Carnegie Mellon University MSCF
public void Greet() { MessageBox.Show("Hello " + m_userName); } public static void Main(String[] a) { WindowGreeting wg = new WindowGreeting(); wg.UserName = "Mike"; wg.Greet(); } } Carnegie Mellon University MSCF
GUI Programming (2) csc -r:System.Windows.Forms.dll NewOne.cs NewOne The escape key works too. Carnegie Mellon University MSCF
GUI Programming (2) using System; using System.Drawing; using System.Windows.Forms; // Inherit from Form to control window public class WindowGreeting : Form { private String m_userName; private Button m_btnClose; private Label m_label; public WindowGreeting() { Console.WriteLine("constructing"); m_label = new Label(); m_label.Location = new Point(16,16); m_label.Size = new Size(136,24); m_label.Text = ""; Carnegie Mellon University MSCF
m_btnClose = new Button(); m_btnClose.Location = new Point(48,50); m_btnClose.Size = new Size(56,24); m_btnClose.Text = "Discard"; m_btnClose.Click += new EventHandler(CloseButton_Click); this.Controls.Add(m_label); this.Controls.Add(m_btnClose); this.ClientSize = new Size(150, 90); this.CancelButton = m_btnClose; } Carnegie Mellon University MSCF
void CloseButton_Click(Object sender, EventArgs e) { this.Close(); } public String UserName { set { m_userName = value; } get { return m_userName; } } public static void Main(String[] a) { WindowGreeting wg = new WindowGreeting(); wg.ShowDialog(); } } Carnegie Mellon University MSCF