Intermediate topics in C#

Ivan Lumala
Academic Developer Evangelist ivanl@microsoft.com

Intermediate C#
 


1st class component support Operator overloading Versioning Attributes

Component Support

What defines a component?


Properties, methods, events Integrated help and documentation Design-time and runtime information Not naming patterns, helper classes, etc. Not external files

C# has first class support
 

Easy to build and consume

Properties
 

Access to private fields normally requires accessors and mutators Properties allow access to private fields as if they were public

public class Person { private int age; public int Age { Property get { return age; } set { age = value; Console.WriteLine(age); } } }

Person p = new Person(); p.Age = 27; p.Age++;

C#

instead of:

Other

Person p = new Person(); p.setAge(27); p.setAge(p.getAge() + 1);

Indexers

Index an object as if it were an array
C#
Numbers Num = new Numbers(); Num[0] = 5; int Val = Num[0];

public class numbers { private int[3] nums; public int this[int index] { get { return nums[index]; } set { nums[index] = value; } } }

instead of:
Numbers Num = new Numbers(); Num.Set_Nums(0,5); int Val = Num.Get_Nums(0);

Indexer

Other

Delegates

Object oriented function pointers

A reference type encapsulating a method signature and return value

 

Can point to multiple functions

Thread-safe + and - operations Delegate

Foundation for events
Multicast Delegate
delegate void Greeting(); Greeting greeting; greeting += new Greeting(A.SayHello); greeting += new Greeting(A.Bow); public class a { void SayHello() { //Say Hello } void Bow() { // bow } }

delegate double Func(double x); Func func = new Func(Math.Sin); double x = func(1.0);

public class math { double Sin(double x) { //return (sin x) } }

Events
  

Specialized multicast delegate Represent a signal that something has occurred in a program Two main issues
 

Generating events Consuming events

Events
Sourcing

Define the event signature

public delegate void SomeDelegate(object sender, EventArgs e);

Define the event and firing logic

public class Button { public event SomeDelegate Click; protected void OnClick(EventArgs e) { if (Click != null) Click(this, e); } }

Events
Handling

Define and register event handler

public class MyForm: Form { Button okButton;
public MyForm() { okButton = new Button(...); okButton.Caption = "OK"; okButton.Click += new SomeDelegate(OkButtonClick); } void OkButtonClick(object sender, EventArgs e) { ShowMessage("You pressed the OK button"); } }

Intermediate C#

Code example of Event Handling in a Windows Form IsPrime app

Intermediate C#
 


1st class component support Operator overloading Versioning Attributes

Rational Number
½, ¾, 1½
Rational r1 = new Rational(1,2); Rational r2 = new Rational(2,1); Rational r3 = r1.AddRational(r2); double d = Rational.ConvertToDouble(r3);

Rational r1 = new Rational(1,2); Rational r2 = 2;
Rational r3 = r1 + r2;

double d = (double) r3;

Rational Number – Struct
public struct Rational { public Rational(int n, int d) { … } public int Numerator { get{…} } public int Denominator { get{…} } public override string ToString() { … } }

Rational r = new Rational(1,2); string s = r.ToString();

Implicit Conversions

No loss of data

public struct Rational { … public static implicit operator Rational(int i) { return new Rational(i,1); } }

Rational r = 2;

Explicit Conversions

Possible loss of precision and can throw exceptions

public struct Rational { … public static explicit operator double(Rational r) { return (double) r.Numerator / r.Denominator; } }

Rational r = new Rational(2,3); double d = (double) r;

Operator Overloading
 

Static operators Must take its type as a parameter

public struct Rational { … public static Rational operator+ ( Rational lhs,Rational rhs) { return new Rational( … ); } } Rational r3 = r1 + r2;
r3 += 2;

Equality Operators

.NET Framework equality support
public override bool Equals(object o)

.Equals() should use operator==()

public static bool operator== (Rational lhs, Rational rhs) public static bool operator!= (Rational lhs, Rational rhs)

if ( r1.Equals(r2) ) { … } if ( r1 == r2 ) { … }

if ( !r1.Equals(r2)) { … } if ( r1 != r2 ) { … }

Intermediate C#
 


1st class component support Operator overloading Versioning Attributes

Versioning

C# added some smarts to fix the version problem.

Problem was that user could not express versioning intent Can enable ( explicit override) Can encourage ( smart defaults) Explicit interface implementation Overloading and overriding readonly fields Smart defaults for accessibility and virtuality Event arguments packaged as objects

C# can't guarantee versioning, but …
 

Impact on language is subtle but pervasive
    

Method Versioning in C#
class Base // // v2.0 v1.0 { } public virtual voidFoo() int Foo() { Database.Log("Base.Foo"); return 0; } } } } class Derived : Base // v1.0 v2.0 { public virtual voidvoid Foo() new virtual Foo() override void Foo() { Console.WriteLine("Derived.Foo"); super.Foo(); } Console.WriteLine("Derived.Foo"); } } }

Intermediate C#
 


1st class component support Operator overloading Versioning Attributes

Attributes

How do you associate information with types and members?
  

Documentation URL for a class Transaction context for a method XML persistence mapping
Add keywords or pragmas to language Use external files, e.g., IDL, DEF

Traditional solutions
 

C# solution: Attributes

Attributes
 

Appear in square brackets Attached to code elements

[HelpUrl(“http://SomeUrl/Docs/SomeClass”)] class SomeClass { [WebMethod] void GetCustomers() { … } string Test([SomeAttr] string param1) {…} }

Attribute Fundamentals
 

Can be Intrinsic or Custom Attributes are generic classes!
class HelpUrl : System.Attribute { public HelpUrl(string url) { … } … }

Easy to attach to types and members
[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)] class SomeClass { … }

Attributes can be queried at runtime
Type type = Type.GetType(“SomeClass”); Attribute[] attributes = type.GetCustomAttributes();

Creating Attributes

Attributes are simply classes

Derived from System.Attribute Class functionality = attribute functionality

public class HelpURLAttribute: System.Attribute { public HelpURLAttribute(string url) { … } public string URL { get { … } } public string Tag { get { … } set { … } } }

Using Attributes

Just attach it to a class

[HelpURL(“http://someurl/”)] Class MyClass { … }

Use named parameters

[HelpURL(“http://someurl/”, Tag=“ctor”)] Class MyClass { … }

Use multiple attributes

[HelpURL(“http://someurl/”), HelpURL(“http://someurl/”, Tag=“ctor”)] Class MyClass { … }

Querying Attributes

Use reflection to query attributes

Type type = typeof(MyClass); foreach(object attr in type.GetCustomAttributes()) { if(attr is HelpURLAttribute) { HelpURLAttribute ha = (HelpURLAttribute) attr; myBrowser.Navigate(ha.URL); } }

Resources

Newsgroup:
microsoft.public.dotnet.languages.CSharp on

 

msnews.microsoft.com Web sites:

http://msdn.microsoft.com/ “Inside C#” – MS Press “C# Language Specification” – MS Press “C# How to Program” – Prentice Hall
developmentor, Wintellect http://www.microsoft.com/net/training.asp

Books
  

Training
 

The .NET Framework in Curriculum
 Multi-language
 Use

runtime environment

the language you like  Access the same class libraries to do similar tasks
 Use

a powerful IDE to access easy-to-use learning tools
 Visual

Studio .NET Academic

 Experience

programming with .NET by building your own Terrarium creature

Microsoft Resources for Faculty
 MSDN

Academic Alliance

 Check

out MSDN AA  New program from Microsoft
 Software

for computer science courses

 Annual

membership fee of $799 per department
 Membership

runs from July-June

 Web

site that supports program: (www.msdnaa.net)

 Visual
 All

Studio .NET Academic

the features of Visual Studio .NET Professional plus Course Management Tools

Questions?

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.