one of the most prevalent powerful programming languages
DESCRIPTION
C#. One of the most prevalent powerful programming languages. Hi, C#. class Program { static void Main() { System.Console.Write("Hi"); } }. C# Reads C-Sharp Is a computer programming language Server Side Asp.net Client Side SilverLight Is an ECMA standard, spearheaded by MS. - PowerPoint PPT PresentationTRANSCRIPT
One of the most prevalent powerful programming languages
Hi, C#
class Program{
static void Main(){
System.Console.Write("Hi");
}}
C#Reads C-SharpIs a computer programming language
Server Side Asp.net
Client Side SilverLight
Is an ECMA standard, spearheaded by MS
Run on .net frameworkDeveloped in, say, Visual StudioFor all kinds of software
Web, Service, etc silverlight
Windows Form,
TypedEvery value is typedC# is strong typed, different from ES
Every value is introduced after type declaredThe type cannot be changed all the val’s life.
Type before InstanceEvery value is an instance of a type.Many instances are abstracted by type
Each instance can have their own state Stored in each instance
Their behaviors are of the same model Stored in type. Vary due to data of each instance
Type definition and instantiationIn C#,
We define types, the model Behavior/events Data storage space, field
Instantiate Create a new thing from the model Store different values in the data field.
Type definition and instantiationNote,
Type can have its own behavior/data, which will
not be copied/referenced by instances. Such as constant/static ones
Other members can be inherited
Run!Call a type/instance’method
In which other methods may be calledData may be changedThen stop.
CodingSo in c#, the coding is about typing and
instantiatingTypes first.
Kinds of Types by declarationenumstructclassinterfacedelegate
By referenceenumstruct
classinterfacedelegate
byValue
byReference
By val vs by refBy val By ref
Literal in var Pointer in varLiteral in another place
long i=1; object a=1;
1 1A3D136ui a
1
Types vs TypesSubtype
Any instance of a is also instance of bAssociation
A’s property is b
SubTypeObject
Number
StudentInteger
Negative
Person
Male
Negative Integer
Student Male
FunctionColor
Object always top
Directional
Inherit from multiple
Supertype chain can be 0,1,2, … steps long.The instance of a type is also instance of any type on the supertype chain
Examplepublic enum Color{
Red,Blue,Green
}
Syntax
Case sensitiveType’s initial is conventionally capitalized
Type def comprises signature and body
{static} {public/…} {abstract/sealed} TypeKeyword typename:supertype[1],…{…//the body
}
Signature Modifiersstatic
No instance can be created; not inheritable.access
public: Visitable everywhereprivate: only hereinternal: in this project/packageprotected: in the subtypesprotected internal: subtypes or within package
abstractNo instance; subtype can
sealedNo inheritace
membersDefine:
FieldsConstructor/destructorMethods/properties/indexerEventsInner types
ChessBoard Square-used only here
Different for declaration kinds of types
Fieldclass Student{
public string id;private DateTime dob;
}
//Note the type and varName
ctor
To init fieldsNo returnCan take argsSame name as classTypes with no fields have no ctor
class Student{Sex sex;public Student(Sex sex){
this.sex=sex;
}}
destructor
Clear up, e.g., release held resources such as db.No returnClass name preceded by ~Not necessary
Often explicitly done by other methods like close/Finalizer/destroyer, etc
public class Student{~Student{
//close database, for example}
}
Methodclass Stduent{
public int age(){//return currentTime-dob;
}
}
Propertyclass Stduent{
public bool performance{protected get{
//return grades;}private set{
//forbid}
}
}
//property is like a method without parameter
Indexerpublic class HbueStudent{
public Student this[int x]{//return student one by one
}
}HbueStudent hs=new HbueStudent();hs[0];//a student//note the keyword this. //it’s like a method
Event
Event is a field where a series of methods wrapped as delegates will be triggered.
Static memberpublic class Circle {
static public double Tau=6.28;double area(){
//}
}
//Note if a member is static, it’s a member of the type itself.
//It cannot be inherited. For exmaple Disc inherit Circle’s area, but Circle.Tau insteadof Disc.Tau
enumpublic enum Sex{
Male,Female
}
//Male can be regarded as the static property of Sex, so its initial is capital.
//Object is implicitly the supertype. can not inherit any ther.
//By value//stored as int//used like:
Sex s=Sex.Male;
structpublic struct Point{
double X;double Y;public void Translate(){
…}
}
//note struct has only one implicit supertype object.
interfaceinterface IShape {
public double area();//…
}
// no field; no implementation;//implementation will be in classes subtypes//it’s a placeholder for multiple inheritance,
as is impossible for class
classpublic class Student{
//fields//methods//properties//indexer//event//subtypes
}
delegatepublic delegete double BiOp(double x, double
y);
//inherit Delegate/MultiDelegate implicitly//can only store corresponding functions
BiOp a=(double x, double y)=>return x+y;BiOp b=()=>return;//wrong!
Use your defined type to introduce a var
Student s;Color c;BiOp o;Ishape shape;Point p;
new
s=new Student();
Invoke members
s.run(); //method, in which other instances might be created and invoked
s.sex; //data
Console applicationWe can code different projectsConsole is a simple one
In VSAn application is a project or many projects
When creating projects, select Console, select c# as the lang.
One or more files/folders will be added to the project.C# source code file’s extension is .cs
CodingOne and only one class has a static Main
method The system will invoke this type’s Main and
start the application.
C#
windows
solution
project
Source code opend
subitem
Hi, C#
class Program{
static void Main(){
System.Console.Write("Hi");
}}
struct and enum is where to hold literal valuesclass type declaration is where to hold
functions/fieldsVar of such type is a referenceInstances hold fields
delegate/interface is references
The reference chain will finally lead to literal values.
Class vs struct
reference value
In most cases, the two might both do.
Class vs interface
Having instances
Single inheritance
No instance
Multiple inheritance
Reference type
Why interfaceMultiple inheritanceConceptual, type diagram
You don’t have to care much about detail
Classclass is the most used typestatic void Main method of a class is the entry
point of a program.
Type diagramIn visual studio
Draw diagram to illustrate the subtype relationsYou can also add members to types on the
diagramVisual studio will generate the source code for
you.
ConstructAn instance has all the fields along the
subtype chain.Its constructor will call supertype[1]’s
constructor, which in turn will call upward, and so on, till object, where constructor init fields, then return,
letting the lower chain to init subtype’s fields.This process ensures supertype’s fields initiated
before subtype’s constructor reference those fields in its running.
constructAn instance’s constructor can designate which
of the supertype’s constructor to be calledThe default one is the one with no paras.
destructDestruction from bottom up.
virtual overrideA member can be
overridden in subtypeA{
virtual m(){}}B:A{
override m(){}
}A b=new B();b.m(); //call B.m()
Override vs overload
Overload iswithin a same type where methods of
the same name taking different type
of paras
Override isAbout the
inheritance among types
Method of the same name in subtype overrun that in supertype.
PolymorphismFor instances of the same type, but of
different subtypes,Same-named methods might be different due
to overriding.
E.g. All animals will eat, but the ways of eating differ
Func<int, int> a=(int x)=>x+1;
C# Delegates and Events
Defining and using Delegates three steps:
1. Declaration2. Instantiation3. Invocation
C# Delegates and Events
Delegate Instantiationdelegate void MyDelegate(int x, int y);
class MyClass{ private MyDelegate myDelegate = new MyDelegate( SomeFun );
public static void SomeFun(int dx, int dy) { }
static public void Main(){myDelegate(3,5);
}}
Type declare
instantiate
Event
public delegate void FireThisEvent();
class MyEventWrapper{ private event FireThisEvent fireThisEvent;
public void OnSomethingHappens() { if(fireThisEvent != null) fireThisEvent(); }
public event FireThisEvent HandleFireThisEvent { add { fireThisEvent += value; } remove { fireThisEvent -= value; } }}
//somewhere else, someone will add to the events. And when something happens, onSomethingHappes will fire all the delegate in that events.
[…]class A{
[…]void m(){}
}
AttributesQuerying Attributes
[HelpUrl("http://SomeUrl/MyClass")] class Class1 {}[HelpUrl("http://SomeUrl/MyClass"), HelpUrl("http://SomeUrl/MyClass”, Tag=“ctor”)] class Class2 {}
Type type = typeof(MyClass); foreach (object attr in type.GetCustomAttributes() ) { if ( attr is HelpUrlAttribute ) { HelpUrlAttribute ha = (HelpUrlAttribute) attr; myBrowser.Navigate( ha.Url ); }}
The End
Thanks