2. C# and OOP
C# is designed for the .NET Framework
The .NET Framework is Object Oriented
In C#
Your access to the OS is through objects
You have the ability to create first class
objects
The FCL is designed for extension and
integration by your code
3. Defining Classes
class Name:BaseType{
// Members
}
Namespace NameName{
class Name:BaseType{
}
}
class MyType{
public static String someTypeState;
public Int32 x;
public Int32 y;
}
4. Accessibility
In C#, private is the default accessibility
Accessibilities options
public – Accessible to all
private – Accessible to containing class
protected – Accessible to containing or derived classes
internal – Accessible to code in same assembly
protected internal – means protected or internal
Classes can be marked as public or internal
By default they are private
Accessible only to code in the same source module
5. Type Members in C#
Fields
The state of an object or type
Methods
Constructors
Functions
Properties (smart fields)
Members come in two basic forms
Instance – per object data and methods
Default
Static – per type data and methods
Use the static keyword
6. Methods
Declared inline with type definition
class MyType{
public Int32 SomeMethod(){
return x;
}
public static void StaticMethod(){
// Do something
}
}
No inline keyword, methods are inlined
when appropriate by the JIT compiler
7. Properties
Methods that look like fields (smart fields)
class Point{
Int32 x;
Int32 y;
public Int32 X{
get{return x;}
set{x = value;}
}
public Int32 Y{
get{return y;}
set{y = value;}
}
}
Can have read-only or write-only properties
9. Instance Constructors
Constructors are used to initialize fields
You can implement simpler constructors in terms of more
complex ones with the this keyword (suggested)
class Point{
Int32 x;
Int32 y;
public Point():this(0, 0){}
public Point(Int32 x, Int32 y){
this.x = x;
this.y = y;
}
}
You can indicate which base constructor to call
Use the base keyword
10. Type (static) Constructors
Type constructors are used to initialize
static fields for a type
Only one static constructor per type
Called by the Common Language Runtime
Guaranteed to be called before any reference to
the type or an instance of the type
Must have no parameters
Use the static keyword to indicate a type
constructor
11. Derivation and Object
All types in the system are derived from Object
You can specify a base class
Without a base class the compiler assumes Object
Object reference variables are used as generic
references
Collection classes in the Framework Class Library
Object implements useful methods like
ToString(),GetType()
ReferenceEquals()
12. Polymorphism and Virtual Functions
Use the virtual keyword to make a method virtual
In derived class, override method is marked with the
override keyword
Example
ToString() method in Object class
public virtual string ToString();
Example derived class overriding ToString()
class SomeClass:Object{
public override String ToString(){
return “Some String Representing State”;
}
}
Polymorphism.cs
13. C# and Events
C# has built in support for events
Great for dealing with objects in an event-driven
operating system
Improved performance and flexibility over an all-
virtual-function solution
More than one type can register interest in a
single event
A single type can register interest in any number
of events
14. Handling an Event
EventHand.cs
using System;
using System.Windows.Forms;
class MyForm:Form{
MyForm(){
Button button = new Button();
button.Text = "Button";
button.Click += new EventHandler(HandleClick);
Controls.Add(button);
}
void HandleClick(Object sender, EventArgs e){
MessageBox.Show("The Click event fired!");
}
public static void Main(){
Application.Run(new MyForm());
}
}
16. Defining an Event
Based on a callback mechanism called a delegate
class EventInt{
Int32 val;
public Int32 Value{
get{return val;}
set{
if(Changed != null)
Changed(value, val);
val = value;
}
}
public event Callback Changed;
public delegate
void Callback(Int32 newVal, Int32 oldVal);
}
EventInt.cs
17. Callback Methods (Delegates)
Delegates.cs
using System;
delegate void MyDelegate(String message);
class App{
public static void Main(){
MyDelegate call = new MyDelegate(FirstMethod);
call += new MyDelegate(SecondMethod);
call("Message A");
call("Message B");
}
static void FirstMethod(String str){
Console.WriteLine("1st method: "+str);
}
static void SecondMethod(String str){
Console.WriteLine("2nd method: "+str);
}
}
18. Interfaces
C# supports interfaces
Your types can implement interfaces
Must implement all methods in the interface
You can define custom interfaces
Interfaces can contain methods but no fields
Propertiesand events included
Constructors are not supported in interfaces
Use the interface keyword
interface Name{
// Members
}
Sortable.cs
19. Operator Overloading and Type
Conversion
C# allows you to write operator overload
methods
Called when a custom type is used in an
expression with operators
Can overload: +, -, *, |, etc.
Can create custom cast methods
Implicitlyor explicitly convert your type to
another type
Overloading.cs TypeConverters.cs
20. C# and OOP
C# and the .NET Framework promote
component development
Can use binary or pre-compiled objects
More applications will use more components
Creates a market for third-party component
venders
Strong security story allows for internet
deployment of objects
C# has a great set of tools for the object
oriented programmer
Sample Dialog: Speaker Instructions: You should introduce yourself on this slide. Briefly address the topic of the evening and mention the length of the presentation. You can also discuss the nature of your organization (user group, etc.) while on this slide.
Sample Dialog: You probably already know that C# is one of the most popular programming language choices for writing software that targets the .NET Framework. The .NET Framework itself is a completely object oriented platform, and C# is a first class object oriented programming language to complement this platform. In C# your software’s access to the system is through objects, meanwhile your application and application logic is managed as objects. Finally, the Framework Class Library is designed for extendibility. It is natural to extend the classes in the FCL, so that your application’s objects blend right in with the library objects. Speaker Instructions: Anybody who knows about C# probably already knows that it is object oriented, etc. So this slide is really just here to introduce (briefly) the relationship between C# and the .NET Framework, etc, for those who know very little about the products.
Sample Dialog: C# is a a language with C++-based syntax much like Java is derived from C++. To define a class you use the class keyword, your classes name, and base class. C# supports namespaces. Every type in the Framework Class Library exists in a namespace. You should give your reusable types a namespace as well, however it is less necessary for your application classes to be in a namespace. This last example shows a class that does not explicitly declare a base class, so it is implicitly derived from Object, and it also shows the definition of a couple of fields in the type. Speaker Instructions:
Sample Dialog: Like C++ and Java, C# supports member and class accessibility. The default accessibility is private, and you must decorate members with an accessibility modifier to set a different accessibility. The most common accessibilities are public, private, and protected. However, C# introduces the idea of an internal accessibility which allows access by any class in the same binary assembly file. This is similar to, but more flexible than the C++ friend class. Speaker Instructions: You could spend forever talking about accessibility. If you like you can edge into the direction of design by saying that fields should be private, and methods can be public, etc. But be careful, because you could sink ten minutes on this slide alone.
Sample Dialog: In C# like any other object oriented language, the members in a type are basically either fields or methods. However, C# has a rich selection of field and method options. Fields are the data or state of an object or type, and methods are the functionality. Members come in two basic forms, instance and static. Instance members are the most common, and there will be one per instance or object. Static members are shared amongst instances and are one per type. Instance methods require an instance to be called, but static methods can be called directly just using the name of the type. The automatic “this” parameter is passed to instance methods, but not static methods. In .NET or managed code it is a common design pattern to create a class that cannot be instantiated, with nothing but static methods. This is a way of creating methods that are sort-of global, but are still logically grouped with other related methods. The System.Console class is an example of this design pattern. Speaker Instructions: You don’t have to say the stuff in that last paragraph, but concrete examples like these do help to nail down the ideas for the listeners.
Sample Dialog: Methods in C# are declared inline of the class definition. This means that the entire implementation of a class must exist in a single source module. In this example I define a MyType class which defines a single instance method and a single static method. Speaker Instructions: My of the slides in this presentation have little on them but code. In these slides you should point out the relevant pieces of the source code. Depending on your presentation equipment, you may be able to point to the code with your hand, or you can use the mouse pointer to run down the different parts. This helps the watcher to follow along.
Sample Dialog: Properties are a cool kind of method that looks like a field when it is accessed in code. This makes for very readable code that still adheres to the object-oriented guideline of making all fields private. You can make your fields private, and allow access via public properties. In this example the Point class defines private x and y fields, and then it defines two public properties which just access the fields directly. You can put any kind of code that you like in the get and set methods of a property, including validation code, event notification code, or just about anything. In fact, it isn’t even necessary for a property to be backed by an actual field. Speaker Instructions: Properties are a great feature of C#. Be sure to understand them so that you can properly sell this idea. It is a strong feature for OO programmers.
Sample Dialog: Now I am going to switch over to source code and show you the use of a simple class, that also defines properties. Speaker Instructions: You should compile the following code, and step through it. Take the time to explain how it works a bit, and show the code stepping into a property method. using System; class Point{ Int32 x; Int32 y; public Int32 X{ get{return x;} set{x = value;} } public Int32 Y{ get{return y;} set{y = value;} } } class App{ public static void Main(){ Point p = new Point(); p.X = 10; p.Y = p.X+5; Console.WriteLine(p.Y); } }
Sample Dialog: C# supports constructor syntax much like C++. However, unlike C++ it is invalid to call a constructor method directly, so if you wish to implement a constructor in terms of another constructor you must use the special colon-this notation you see here. In this example, the simpler Point() constructor automatically calls the more complex constructor with the default x and y values of 0. Speaker Instructions: FYI, it is recommended that you have only one constructor for a type, and that the rest of the constructors be implemented in terms of this one. However, this is not always possible and must be handled on a type-by-type bases.
Sample Dialog: Static or type constructors are a great feature of C# that did not exist in C++. Type constructors are used to initialize static data for a type. A type constructor is called before any other reference to a type is made. However, other than this promise, the Common Language Runtime does not make any promises of when type constructors will be called. The code in your type constructors should be kept simple, and should not block. Speaker Instructions: The type constructor gets rid of the need to check for static initialization in each call to an instance constructor before getting down to the business of initializing an instance. This simplifies type definitions in C# over C++.
Sample Dialog: In C# all types are derived from Object. Often this is transparent to the developer, but sometimes it can be useful. For example, Object reference variables can be used as generic references that can reference any type. Also, Object itself implements several useful methods that can be used on any type, such as the GetType() method, that can be used for type checking of an object. The virtual ToString() method is also useful for debugging types. Finally, the Object class implements a couple of static methods, the most useful of which is the ReferenceEquals() methods which let you test two object references to see if they refer to the same instance in memory. Speaker Instructions:
Sample Dialog: To create a virtual function in C# you must attribute your method with the virtual keyword. Virtual methods can be public, protected, or protected internal. To override a virtual method in a derived class you must explicitly indicate your intent using the override keyword. Your derived method must also match the base method signature exactly. Speaker Instructions: The override keyword is actually part of the versioning story in the .NET Framework. But this is probably a bit too much to explain in the discussion. However, for your own study you may want to look up the “override” and “new” keywords in the documentation, as this is an example of a feature that is much more well thought out than the equivalent feature in Java.
Sample Dialog: C# has built in support for event notification and handling, which is great for dealing with OSs that are becoming increasingly event driven. Events in C# are very flexible compared to the virtual-function method of responding to system events. Speaker Instructions: We have several slides on this, so you don’t have to say everything on this slide.
Sample Dialog: The source code on this slide shows a simple class derived from Form. The interesting part, however, is how the class registers its interest in the Click event defined by an instance of the Button class. The MyForm class indicates which of its methods (in this case the HandleClick method) should be called when the event is fired. Speaker Instructions: This code is a demo on the next slide
Sample Dialog: Speaker Instructions: There is no dialog on this slide, because really the dialog from the last slide goes with this demo. You can do the two together. You should at least run this code, and perhaps step through it putting a break-point in the Handle method. This helps to drive the event concept home.
Sample Dialog: Using events is common in C# code, but from time to time you will also want to define an event for your own type that you fire at the appropriate time. This code shows an example of a simple class that fires an event whenever a value of one of its properties is changed. (Normally events are fired as a result of external events, but this shows the idea here). The event is named Changed, and is of type Callback. The Callback type is actually a special type called a delegate, which is the managed code version of a function pointer. The delegate definition defines how the event-handler method must be defined, and what parameters it must accept. Then, when it is time to call the code, the event variable is checked for null, and if it is not null, it is used as though it were a method, which causes all of the registered handlers to be called. Speaker Instructions: This can be confusing, and you should definitely point out the code as you describe the different parts. By the way, if this is confusing to you, just compile and run this code, and try changing some things here and there, it becomes clear quickly when you do this.
Sample Dialog: As I mentioned on the previous slide, callback methods themselves are actually implemented using a special type called a delegate. The delegate type can be used directly without events. The framework class library does this from time to time, when it needs a callback, such as when you start a thread, or fire-off an asynchronous method. When you use the delegate keyword in C#, even though it looks like a method definition, it is really a new type definition for maintaining a reference to a method that matches the parameter list and return type of the delegate. This code creates two instances of the MyDelegate delegate, one each for the two methods here. Then the delegate chain is called which is the same syntax as calling into an event. Each time the delegate chain is called, both methods are executed. Speaker Instructions: Again this is an example of code that becomes much more clear once you run it. I strongly suggest that you try this code before attempting to describe the ideas in front of a group of people.
Sample Dialog: Interfaces are an excellent way for a type to take on a role without being derived from a type that defines this role. For example, two totally unrelated types can be sortable and therefore take on the well-defined ability to be sorted, even though they are not derived in the same derivation hierarchy. This is possible through interfaces. In C# you cannot have multiple base classes, but a type can implement any number of interfaces. You will find that you implement pre-existing interfaces often, but from time to time you will have to define your own interface. Interfaces can include only methods, properties, and events. It is not valid for an interface to include a field. Interfaces are defined using the interface keyword as shown here. Speaker Instructions:
Sample Dialog: C# has support for operator overloading and type conversion methods. With operator overloading and conversion methods, you can make it so a custom type can be used in expressions with operators such as plus, minus, and assignment. Operator overloading can be very useful when defining custom math types, however, there are also uses unrelated to math types. For example, the C++ standard template library uses the left shift and right shift operators to indicate input and output from stream objects. This is a unique use of operator overloading that makes for readable code, and C# is flexible enough to be used in similar ways. Speaker Instructions:
Sample Dialog: In general, C# is similar to but more feature-full than C++ in terms of its object oriented abilities. However, one area where C# far-outshines C++ is in the use of binary objects. C# is designed in such a way that you can define an object, and compile it into a binary or assembly file. Then programmers can still use the object in its binary form in their own code, they can derive from it, or do anything that they would be able to do if they actually had the sources. This kind of binary modularity really opens up the market for component development. Applications moving forward will be much more component based. The .NET Framework and C# also has a very strong security model that allows for derivation and use of objects from third parties that are deployed over the internet. And even though you are downloading code and running it locally, you need not worry about code modification, or tampering with your system. C# is a first class language for object oriented programming. Speaker Instructions:
Sample Dialog: Speaker Instructions: Open the floor to questions