Introduction to C# John K. Bennett with thanks to: Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation
Key Language Features Unified object system Everything is an object, even primitives Single inheritance Interfaces Specify methods & interfaces, but no implementation Structs A restricted, lightweight (efficient) type Delegates Expressive typesafe function pointer Useful for strategy and observer design patterns Preprocessor directives
What’s an Object? 1. A set of data, together with … 2. Methods that manipulate that data
Key Ideas about Objects Information Hiding Code Reuse Abstraction Modularity Encapsulation Inheritance Polymorphism
How These Ideas are Implemented : Classes Instances
C# – The Big Ideas A component oriented language Component concepts in C#: Properties, methods, events Design-time and run-time attributes Integrated documentation using XML Enables one-stop programming No header files, IDL, etc. Can be embedded in web pages
C# – The Big Ideas Everything really is an object Traditional views C++, Java: Primitive types are “magic” and do not interoperate with objects Smalltalk, Lisp: Primitive types are objects, but at great performance cost C# unifies with no performance cost Deep simplicity throughout system Improved extensibility and reusability New primitive types: Decimal, SQL… Collections, etc., work for all types
C# – The Big Ideas Robust and durable software Built-In Garbage collection No memory leaks and stray pointers Exceptions Error handling is not an afterthought Type-safety No uninitialized variables, unsafe casts Versioning Pervasive versioning considerations in all aspects of language design
C# Versioning Example
C# Basic Syntax Case-sensitive Whitespace has no meaning Sequences of space, tab, linefeed, carriage return Semicolons used to terminate statements (;) Curly braces { } enclose code blocks Comments: /* comment */ // comment /// <comment_in_xml> Automatic XML commenting facility
Classes and Objects A class combines together Data Class variables Behavior (code for manipulating these data) Methods This is a key feature of object-oriented languages Class and Instances Class defines a “template” Instances of a class represent reified, well, instances Each instance gets its own copy of the class variables; except “static” methods and variables are unique to the class. Example: Class Person, where each instance has a unique age, height, name, etc.; the static class variable numPersons keeps track of how many instances of Person we have created.
Inheritance How it Works If class B inherits from base class A, it gains all of the variables and methods of A Class B can optionally add more variables and methods Class B can optionally “override” (change) the methods of A Uses Reuse of class by specializing it for a specific context Extending a general class for more specific uses Interfaces ( a language feature) Allow reuse of method definitions of interface Subclass must implement method definitions
Inheritance Example class A { public void display_one() { System.Console.WriteLine("I come from A"); } } class B : A { public void display_two() { System.Console.WriteLine("I come from B, child of A"); } } class App { static void Main() { A a = new A(); // Create instance of A B b = new B(); // Create instance of B a.display_one(); // I come from A b.display_one(); // I come from A b.display_two(); // I come from B, child of A } }
Inheritance Qualifiers Abstract indicates an incomplete implementation. can be used with classes, methods, properties, indexers, and events. When used with classes, indicates a class intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented (overridden) by classes that derive from the abstract class. Virtual used to modify a method, property, indexer, or event declaration may be overridden in a derived class. public abstract class myBase { // If you derive from this class you must implement this method. notice we have no method body here either public abstract void YouMustImplement(); // If you derive from this class you can change the behavior of this method, but are not required to public virtual void YouMayOverride() { } } public class MyBase { // This will not compile because you cannot have an abstract method in a non-abstract class public abstract void YouMustImplement(); }
Visibility A class is a container for data and behavior Often want to control over which code: Can read & write data 1. Can call methods 2. Access modifiers: public No restrictions. Members visible to any method of any class private Members in class A marked private only accessible to methods of class A Default visibility of class variables protected Members in class A marked protected accessible to methods of class A and subclasses of A.
Visibility Example class A Class A can see: { public int num_slugs; num_slugs: is public protected int num_trees; num_trees: is protected, but is … defined in A } Class B can see: class B : A { num_slugs: is public in A private int num_tree_sitters; num_trees: is protected in … parent A } num_tree_sitters: is private, but class C is defined in B { … Class C can see: } num_slugs: is public in A Can’t see: num_trees: protected in A num_tree_sitters: private in B
Constructors Use “new” to create a new object instance This causes the “constructor” to be called A constructor is a method called when an object is created C# provides a default constructor for every class Creates object but takes no other action Typically classes have explicitly provided constructor Constructor Has same name as the class Can take arguments Usually public, though not always Constructor may be private to ensure that only one object instance is created
Unusual Types in C# Bool Holds a boolean value, “true” or “false” Integer values are not equivalent to boolean values 0 does not equal false There is no built-in conversion from integer to boolean Decimal A fixed precision number up to 28 digits plus decimal point Useful for money calculations Example: 300.5m Suffix “m” or “M” indicates decimal
Variable Examples int number_of_slugs = 0; string name = “Bob”; // string is a built-in Class float myfloat = 0.5f; bool onFire = true; const int freezingPoint = 32; // const = fixed Variables must be initialized or assigned before first use Class members require a visibility def (defaults to private) Constants cannot be changed
Enumeration Example public enum TokenType { KEYWORD, SYMBOL, IDENTIFIER, INT_CONST, STRING_CONST, UNKNOWN}; public TokenType tokenType = TokenType.UNKNOWN; Base type can be any integral type (int, ushort, long), except for char Defaults to int, for example, in the above example “KEYWORD” = 0
If-Else Example using System; if (i < 5) { Console.WriteLine(“i is < 5”); } else { Console.WriteLine(“i is >= to 5”); } C# supports C/C++/Java syntax for “if” statement Expression must evaluate to a bool value No integer expressions here == means “equal to” for boolean comparison if (i == 5) // if i equals 5 if (i = 5) // error, since i = 5 is not a boolean expression
For Statement Example for (int i= 0; i < numShips; i++) { ship[i] = “armed”; } For statement is used to iterate Three parts: (init; test; increment)
While Statement Example // go till we find a quote character while (line[charInLine] != '"') { charInLine++; } charInLine++; // put index on the next character If boolean expression in while statement is false, code in loop is never executed.
Switch Statement Example const int raining = 1; const int snowing = 0; int weather = snowing; switch (weather) { case snowing: System.Console.Writeln(“It is snowing!”); goto case raining; case raining; System.Console.Writeln(“I am wet!”); break; default: System.Console.Writeln(“Weather OK”); break; } Alternative to if-else chains Typically use break; use goto to continue to another case (fall-thru is illegal, except for empty cases)
C# Program Structure Namespaces Contain types and other namespaces Type declarations Classes, structs, interfaces, enums, and delegates Members Constants, fields, methods, properties, indexers, events, operators, constructors, destructors Organization No header files, code written “in - line” No declaration order dependence
Recommend
More recommend