.NET Fundamentals - PowerPoint PPT Presentation


PPT – .NET Fundamentals PowerPoint presentation | free to download - id: 5558e1-ZWJlM


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation

.NET Fundamentals


.NET Fundamentals November 20, 2003 Week 3 Class Agenda November 20, 2003 Questions / Homework? Types (Intrinsic and Reference), Classes, Objects Class Exercise ... – PowerPoint PPT presentation

Number of Views:65
Avg rating:3.0/5.0
Slides: 99
Provided by: Chip167


Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: .NET Fundamentals

.NET Fundamentals
  • November 20, 2003
  • Week 3

Class Agenda November 20, 2003
  • Questions / Homework?
  • Types (Intrinsic and Reference), Classes, Objects
    Class Exercise (Demo ? derived classes
  • Class Exercise
  • Procedural vs Object Oriented Programming
  • Class Exercise
  • Homework Assignment

Questions / Homework ?
  • Common Email List
  • Homework ??
  • Review public/private and static in class this
  • Move last class from Thursday 12/18 to Monday

Course Schedule
Week Topics
1 Introduction to .NET Framework, C
2 C, Windows Forms Programming, Exceptions
3 Types in .NET Classes Objects and Writing Classes Boxing and Unboxing
Week Topics
4 ADO.NET (managed data access) - Connections - Adapters - Data Sets - Grid Control
5 Introduction to the Frameworks Class Library Bootstrapping the Common Language Resource (CLR) Modules and Assemblies .Net Packaging Public and Private Keys Shared Assemblies The Global Assemble Cache (GAC) Strong Names
Week Topics
6 ASP.NET Introduction to Web Services Web Security Advanced Concepts - Serialization - Reflection Web Services Class Project
7 Web Services Class Project (continued)
8 Web Services Class Project (continued)
(No Transcript)
Strongly Typed Object Oriented Programming
Type ? Class ? Object "In C a type is defined
by a class, while the individual instances of a
class are known as objects." Jesse Liberty
Types and Types in .NET
What is a type?
  • Every variable has a type
  • A type defines the variables general properties
    and behaviors
  • A type can be complex like a form class or simple
    like an integer.
  • Sometimes a type is tangible, like a button in a
  • Sometimes a type abstract, like a data table or a

Types in .NET
  • Previously, each programming language represented
    data types in its own way. Now, the common type
    system provides every language in Visual Studio
    .NET with a consistent set of data types.

In addition, every data type supports a minimum
set of methods. Because all languages use the
same library of types, you can call one language
from another without having to convert the type
or the call conventions.
The .NET run-time environment is designed to be
safe and secure. The .NET run-time environment
enforces strict rules to guarantee the safety of
type-safe code
  • Type-safe code is code that accesses types only
    in well-defined, allowable ways.
  • Type-safe code only accesses memory at fixed
    offsets corresponding to actual field members.
  • Code that accesses memory at arbitrary offsets
    outside the range of memory that belongs to that
    object's publicly exposed fields, it is not

.NET and type-safe code
  • The Common Language Specification defines a set
    of programmatically verifiable rules.
  • These rules govern the interoperation of types
    that are authored in different programming
  • These rules also establish requirements for
    Common Language Specification compliance.
  • Visual Studio .NET languages such as Microsoft
    Visual Basic .NET and Microsoft Visual C .NET
    comply with the Common Language Specification.

Type Fundamentals
  • All objects in .NET ultimately derive from
  • This means that every object of every type has a
    minimum set of methods

The Public Methods
  • Equals - Determines whether two objectinstances
    are equal.
  • GetHashCode - Serves as a hash function for a
    particular type, suitable for use in hashing
    algorithms and data structures like a hash table.
  • ToString - Returns a string that represents the
    current object.
  • GetType - Gets the type of the current instance.
  • ReferenceEquals - Determines whether the
    specified object instances are the same instance.

The Protected Methods
  • Methods only seen by derived classes.
  • MemberWiseClone - Creates a shallow copy of the
    current object. Creates a new instance of the
    object and sets the new objects fields to be
    identical to this objects fields. Returns a
    reference to the new object.
  • Finalize - Allows an object to attempt to free
    resources and perform other cleanup operations
    before the object is reclaimed by garbage

Microsoft .NET supports two kinds of data types
  • Value types. Types that are allocated in a stack
    or inline in a structure.
  • Reference types. Types that are allocated in a

Value Types
  • Value types store the data directly on the stack.
    (simply, a last in first out list).
  • You access this data directly.
  • To create a copy of the value that is assigned,
    you can assign a value type to a variable.
  • Value types are not inheritable.
  • They are implicitly derived from the
    System.ValueType class, which derives from

Value Types
  • Value types include
  • primitives
  • enums
  • structs

Primitives are the foundation of data types.
Primitives are the lowest types available. You
can identify primitives through keywords, which
are aliases for predefined types in the System
namespace. For example, the int or int32 data
type is an alias for the System.Int32
object. Because all data types are derived from
System.Object, primitives are actually objects
with a set of members that are available for each
type. For example, the int32 data type has a
member named MaxValue.
Primitive Types
- byte - short - int - long - single -
double - decimal - bool - DateTime -
char - string
  • Of these primitive types, only the string type is
    a reference type. All of the other primitive
    types are value types.

  • The enum keyword is used to declare an
    enumeration, a distinct type consisting of a set
    of named constants called the enumerator list.
    Every enumeration type has an underlying type,
    which can be any integral type except char.

enum example
  • In this example, an enumeration, Days, is
    declared. Two enumerators are explicitly
    converted to int and assigned to int variables.
  • enum Days Sat1, Sun, Mon, Tue, Wed, Thu,
  • int x (int) Days.Sun
  • int y (int) Days.Fri

  • The struct data type inherits from the
    System.ValueType class.
  • A struct type is a value type that can contain
    constructors, constants, fields, methods,
    properties, indexers, operators, events, and
    nested types.
  • A struct is like a light weight class.

  • The .NET structure data type is very similar to a
    class data type except that a structure data type
    is a value type (whereas a class data type is a
    reference type).
  • For increased efficiency, you may want to use
    structure data types if you do not need the
    overhead of maintaining a reference pointer.
    However, because a structure data type is a value
    type, it is not garbage collected.

Reference types
  • Reference types store the data on the managed
    heap and store a pointer to the data on the stack
  • You access the data in reference types through
    the reference pointer
  • Are collected by the garbage collector when they
    are no longer in use.
  • Are passed by reference.
  • Can be extended by inheritance.
  • Can specify Finalizers.
  • Reference pointer is type safe.
  • A variable of reference type always contains a
    reference to a value of that type or a null

Reference types include the following data types
  • String
  • Array
  • Class
  • Interface
  • Delegate

  • .NET String data types are invariant.
  • Because String data types are read-only after
    initialization, you cannot directly modify their
  • The String variable contains a pointer to memory
    that contains the actual data. Any modification
    to the string deallocates the current memory
    block and allocates a new memory block for the
    new value

  • NOTE If the cost of deallocating and
    reallocating string greatly affects performance,
    you can use the StringBuilder class in Visual
    Studio .NET. You will notice performance
    benefits at approximately 300 string

  • Provides methods for creating, manipulating,
    searching, and sorting arrays, thereby serving as
    the base class for all arrays in the common
    language runtime.
  • All array types implicitly inherit from the
    System.Array class, which inherits from
    System.Object. Arrays are allocated on the
    managed heap.
  • If all of the dimensions of the array are zero,
    the array has a length of zero, and the array is
  • In an array reference types are initialized to
    null, value types are initialized to the default
    value for their type (i.e. int members are
    initialized to zero). You can initialize arrays
    during declaration.
  • By inheriting from System.Array, each array
    reference type automatically inherits a set of
    System.Array methods and properties such as Rank,
    Length, GetLength, and GetUpperBound.

  • A class is a data structure that may contain data
    members (such as constants and variables),
    function members (such as methods, properties,
    indexers, operators, events, and constructors),
    and nested types.
  • Class types support inheritance. Inheritance is a
    mechanism whereby a derived class can extend and
    specialize a base class.
  • Derived classes inherit and can extend the
    properties and the methods of the base class.
    Derived classes can also override inherited
    methods with new implementations.

  • An interface is a contract.
  • The class or a structure that implements the
    interface must adhere to the contract.
  • The contract specifies the members that must be
    supplied by the class that implements the
  • The interface is a list of functions. The
    interface contains methods, properties, and
  • An interface provides no implementation itself.

  • The delegate reference type is central to the
    programming model of the common language runtime.
  • Delegates are classes that hold references to
  • The Delegate reference provides a managed,
    type-safe function pointer, which is the delegate
  • A delegate is derived from the System.Delegate
  • Delegates are the basis for events.
  • The .NET event model uses delegates to bind
    events to the methods that are used to handle
    them. The delegate allows other classes to
    register for event notification by specifying a
    handler method. When the event occurs, the
    delegate calls its bound method.

(No Transcript)
Boxing and Unboxing
  • In some cases, you may want to treat an instance
    of a value type like an instance of a reference
    type. Boxing provides this mechanism. Boxing
    converts a value type to a reference type by
    performing the following steps
  • Allocates memory on the managed heap to store the
  • Copies the value to the managed heap.
  • Stores the reference to the data (address of the
    object) on the stack.
  • Unboxing converts an instance of a reference type
    back to its original value type by returning a
    pointer to the data within a boxed subject. The
    pointer does not include the usual overhead that
    is associated with a true object.

  • Heres what happens when you box a value type
  • Memory is allocated from the managed heap to hold
    the value type plus the overhead members.
  • The value types fields are copied to the newly
    allocated memory.
  • The address of the object is returned.
  • Note that a whole new object is returned
    manipulating the original value type will not
    change the boxed reference.
  • int value 123
  • object o value // box int into an object
  • int value2 (int) o // unbox into value2

  • Heres what happens when a reference type is
  • If the reference is null, a NullReferenceException
    is thrown
  • If the reference does not refer to an object that
    is a boxed value of the desired value type, an
    InvalidCastException is thrown
  • A pointer to the value type is returned, which is
    frequently copied immediately to another value
  • int value 123
  • object o value // box int into an object box
  • long value2 (long) o // this throws a cast

  • There are two types of casting
  • Implicit casting. Implicit casting is transparent
    to users. The compiler automatically converts
    from one data type to another. The predefined,
    implicit conversions always succeed and never
    cause an error.
  • Explicit casting. Explicit casts are called in
    the code. Explicit casts cannot guarantee success
    and may lose information if you cast from a
    larger type to a smaller type.

(No Transcript)
Type ? Class ? Object "In C a type is defined
by a class, while the individual instances of a
class are known as objects." Jesse Liberty
In C Everything happens within a Class!
  • A class is a data structure that may contain data
    members (such as constants and variables),
    function members (such as methods, properties,
    indexers, operators, events, and constructors),
    and nested types.
  • Class types support inheritance. Inheritance is a
    mechanism whereby a derived class can extend and
    specialize a base class.
  • Derived classes inherit and can extend the
    properties and the methods of the base class.
    Derived classes can also override inherited
    methods with new implementations.

  • Classes are declared using the keyword class. It
    takes the following form
  • attributes modifiers class identifier
    base-list class-body
  • where
  • attributes (Optional)
  • modifiers (Optional) The allowed modifiers are
    new, abstract, sealed, and the four access
  • identifier The class name.
  • base-list (Optional) A list that contains the one
    base class and any implemented interfaces, all
    separated by commas.
  • class-body Declarations of the class members.

Common Class Members
  • fields, which are the variables of the class.
  • methods, which implement the computations and
    actions that can be performed by the class.
  • properties, which define named characteristics
    associated with reading and writing those

Instance versus Static Members
  • Instance members are unique to each object
    instance and referenced by the object reference.
  • Static members are limited to one copy,
    associated with the class type, being referenced
    by the class type.

  • A field is a member that represents a variable
    associated with an object or class.
  • Fields maintain class state

  • A method is a member that implements a
    computation or action that can be performed by an
    object or class.
  • Choose a name for your method based on the
    following guidelines.
  • Use verbs or verb phrases to name methods
  • The first letter in the identifier and the first
    letter of each subsequent concatenated word are

Method Arguments
  • Appear as local variables within the method
  • Method arguments are private by default

Modifiers for Fields or Methods
Term Description
public Accessible to all methods in all assemblies.
private Method is visible only to member methods within the same class.
protected Method extends visibility to methods of derived classes.
internal Method extends visibility to any class in the same assembly.
protected internal protected or internal
Modifiers for Fields
Term Description
static The field is part of the types state, not the objects state
readonly The field can be written to only in the constructor.
Modifiers for Methods
Term Description
static Method is associated with the type itself, not an instance of the type. The method may not access instance fields.
virtual Most-derived method is called, even if object is cast to a base type. Applies only to non-static methods.
new Method should not override a virtual method defined by its base type the method hides the inherited method. Applies only to virtual methods
Modifiers for Methods (continued)
Term Description
override Explicitly indicates the method is overriding as virtual method in its base type. Applies only to virtual methods.
abstract Indicates that a deriving type must implement the method. Need to mark the type abstract as well. Applies only to virtual methods.
sealed The derived type cannot override this method. Applies only to virtual methods.
Method Overloading
  • Method overloading occurs when a class contains
    two methods with the same name, but different
  • Use method overloading to provide different
    methods that do semantically the same thing.
  • Use method overloading instead of allowing
    default arguments. Default arguments do not
    version well and therefore are not allowed in the
    Common Language Specification (CLS). The
    following code example illustrates an overloaded
    String.IndexOf method.
  • int String.IndexOf (String name)
  • int String.IndexOf (String name, int startIndex)

Method Overloading (continued)
  • Use default values correctly. In a family of
    overloaded methods, the complex method should use
    parameter names that indicate a change from the
    default state assumed in the simple method. For
    example, in the following code, the first method
    assumes the search will not be case-sensitive.
    The second method uses the name ignoreCase rather
    than caseSensitive to indicate how the default
    behavior is being changed.
  • // Method 1 ignoreCase false.
  • MethodInfo Type.GetMethod(String name)
  • // Method 2 Indicates how the default behavior
    of method 1 is
  • // being changed.
  • MethodInfo Type.GetMethod (String name, Boolean

Properties (get and set accessor)
get and set accessor
  • Provides protection for variables in a class
  • Define the variable as private
  • Use a get and set accessor to access the variable
  • The accessor of a property contains the
    executable statements associated with getting
    (reading or computing) or setting (writing) the
    property. The accessor declarations can contain a
    get accessor, a set accessor, or both.

  • using System
  • public class anyClass
  • private string name
  • public string Name
  • get
  • return name
  • set
  • name value

get accessor
  • The body of the get accessor is similar to that
    of a method. It must return a value of the
    property type. The execution of the get accessor
    is equivalent to reading the value of the field.
  • When you reference the property, except as the
    target of an assignment, the get accessor is
    invoked to read the value of the property.
  • The get accessor must terminate in a return or
    throw statement, and control cannot flow off the
    accessor body.

set accessor
  • The set accessor is similar to a method that
    returns void. It uses an implicit parameter
    called value, whose type is the type of the
    property. In the following example, a set
    accessor is added to the Name property
  • When you assign a value to the property, the set
    accessor is invoked with an argument that
    provides the new value. For example
  • It is an error to use the implicit parameter name
    (value) for a local variable declaration in a set
  • When accessing a property using the set accessor,
    preserve the value of the property before you
    change it. This will ensure that data is not lost
    if the set accessor throws an exception.

accessors notes
  • A property is classified according to the
    accessors used as follows
  • A property with a get accessor only is called a
    read-only property. You cannot assign a value to
    a read-only property.
  • A property with a set accessor only is called a
    write-only property. You cannot reference a
    write-only property except as a target of an
  • A property with both get and set accessors is a
    read-write property.
  • In a property declaration, both the get and set
    accessors must be declared inside the body of the

accessors notes continued
  • It is a bad programming style to change the state
    of the object by using the get accessor. For
    example, the following accessor produces the side
    effect of changing the state of the object each
    time the number field is accessed.
  • public int Number get return number //
    Don't do this
  • The get accessor can either be used to return the
    field value or to compute it and return it. For
  • public string Name get return name ! null ?
    name "NA"
  • In the preceding code segment, if you don't
    assign a value to the Name property, it will
    return the value NA.

  • Methods called whenever an object is instantiated
  • Before the constructor is called, the object
    points to undifferentiated memory.
  • After the constructor is called, the object
    points to valid instance.
  • If a constructor is not defined the CLR creates
    one for you.
  • Member variables are initialized to default
  • Constructor method name is the same as the class

Constructor (continued)
  • If you provide an overloaded constructor, you
    must provide a default constructor, even if it
    does nothing.
  • Can call the base class constructor using the
    base keyword.
  • Base class constructor always uses the most
    derived type.
  • Constructors have no return type
  • Typically declared public
  • Arguments are defined just like any other method

Copy Constructor
  • Constructor where the argument is another
    instance of the object
  • Shallow copy shares address of references
    defined in the class
  • Deep copy Duplicates all members throughout the

  • Setting member variables (i.e. fields) to
    specific values when the object is created.
  • int i 12
  • string tmpString "abcd"

this pointer
  • The this keyword refers to the current instance
    of the class.
  • Static member functions do not have a this
  • The this keyword can be used to access members
    from within constructors, instance methods, and
    instance accessors.
  • It is an error to refer to this in a static
    method, static property accessor, or variable
    initializer of a field declaration.

(No Transcript)
Demo Tic Tac Toe Program
  • Walk through a windows form class
  • View the static main method
  • See how the controls are added to the form
  • Implement a common button method
  • View collection of controls

(No Transcript)
Class Exercise CTime Class / Tester
  • see handout.

(No Transcript)
Type ? Class ? Object "In C a type is defined
by a class, while the individual instances of a
class are known as objects." Jesse Liberty
What is an object?
  • A class is an abstract model.
  • An object is the concrete realization or instance
    built on the model specified by the class.
  • An object is created in the memory using the
    keyword 'new' and is referenced by an identifier
    called a "reference".

Creating an Object
  • MyClass myObjectReference new MyClass()
  • In the above, a instance of class MyClass is
    created with the variable name of

The new operator
  • Allocates memory for the object from the managed
  • Initializes the objects overhead members (the
    CLR uses these to manage the object).
  • The objects pointer to the types method table.
  • A SyncBlockIndex (used to manage access to the
    object by multiple thread).
  • Calls the types instance constructor, passing
    any parameters specified. Most languages call
    the base class constructor, but this is not
    mandated by the CLR.

(No Transcript)
Object Oriented Programming
The essence of object-oriented programming is the
creation of new types.
What is an Object?
  • An object is a software bundle of related
    variables and methods.
  • Software objects are often used to model
    real-world objects you find in everyday life.

Object Oriented Programming
  • Where programmers define not only the data type
    of a data structure, but also the types of
    operations (functions) that can be applied to the
    data structure. The data structure becomes an
    object that includes both data and functions.
  • Programmers create relationships between one
    object and another. Objects can inherit
    characteristics from other objects.
  • A principal advantages of object-oriented
    programming over procedural programming is that
    programmers create modules that do not need to be
    changed when a new type of object is added. A
    programmer simply creates a new object that
    inherits many of its features from existing

Procedural Programming
  • Focus on sequential logic flow (i.e. steps in a
    procedure, open file, read records, calculate
    amount, write record, etc.)
  • Focus on verbs (do this, then do this, etc.)
  • Use flowcharts to work logic problems

Object Oriented Programming
  • Focus on the nouns, the things (i.e. customer,
    stockroom, order, etc.)
  • Focus on the relationships (i.e. orders for
    customer, parts for an order, etc.)
  • Verbs are methods (Customer.PlaceOrder,
    Part.CheckInventory, etc.)
  • Use Object Oriented Modeling Tools

Object Oriented Programming Languages
  • For a programming language to be a true OOP
    language, the language must meet the following
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

  • Abstraction manages the complexities of a
    business problem by allowing you to identify a
    set of objects involved with that business

  • Encapsulation hides the internal implementation
    of an abstraction within the particular object.

  • Polymorphism provides for multiple
    implementations of the same method. For example,
    different objects can have a save method, each of
    which perform different processing.

  • poly ? many morph ? forms
  • When all derived types from a common base class
    provide the same method, with implementations
    specific to the derived class.
  • To create polymorphic methods add virtual to the
    base class method.
  • In the derived class add the word override.

  • The OO term for the ability of a type to use and
    extend the functionality of a base type.
  • A class inherits state and behavior from its
  • Inheritance provides a powerful and natural
    mechanism for organizing and structuring software
  • .NET provides for true implementation inheritance
    whereby you can reuse the implementation of a

Implementation Inheritance
  • A class can inherit from a superclass, and
    thereby the subclass derives the implementation
    of the methods in the superclass. The subclass
    can also override some of the methods and extend
    the behavior by adding more methods.
  • One big advantage of implementation inheritance
    is code reuse.
  • Unlike classic C, the CLR (and hence C) does
    not support multiple implementation inheritance.

  • To inherit from is to be a specialized version of

Derivied Class
  • Can not inherit a constructor
  • Must implement its own constructor
  • Can only access the base constructor by calling
    it implicitly

(No Transcript)
C Programming Writing Classes
Homework Build a NameLister Class
(No Transcript)
About PowerShow.com