For example: public class calculator { private double _op1; private double _op2; public double Operand1... For example: public class person { private string _firstName; priva
Trang 1In C# there is no direct distinction between a Sub and a Function, and members are just implemented as functions (that may, or may not, return data) The syntax is:
[ public | protected | internal | protected internal | private | static |
virtual | override | abstract | extern ]
[ type | void ] memberName([parameters])
{
}
The various keywords are described below:
Keyword Description
public The member is publicly accessible
protected The member is only accessible from the containing class or types derived from the containing member internal The member is only accessible from this program Equivalent to Friend in Visual Basic
Table continued on following page
private The member is only accessible from within the containing member
static The member is shared by all instances of the class, and exists independently of a class instance
Equivalent to Shared in Visual Basic
virtual The member can be overridden by a sub-class
override The member overrides an identically named member from a base class, with the same signature The
base class member must be defined as virtual, abstract or override
abstract This member is an abstract member, and must be implemented by a sub-class
extern The member is implemented in an external assembly
For example:
public class calculator
Trang 2For a method that does not return a result, we declare the type as void:
public void updateSomething()
public double Op1;
public double Op2;
public double Add()
Trang 3{
return Op1 + Op2;
}
}
The alternative (and preferred) approach is to use property accessors For example:
public class calculator
{
private double _op1;
private double _op2;
public double Operand1
Trang 4Constructors
Trang 5Rather than using New for constructors, the C# syntax is to use a method with the same name as the class For example:
public class person
{
private string _firstName;
private string _lastName;
Trang 6private string _firstName;
private string _lastName;
Trang 7Inheritance
Inheritance in C# looks more like C++, where a colon (:) is used to separate the class and the base class For example:
public class programmer : person
{
private int _avgHoursSleepPerNight;
public programmer(): base()
Trang 8{
get { return _avgHoursSleepPerNight; }
set { _avgHoursSleepPerNight = value; }
}
}
The class definition defines that our class is called programmer and the base class is called person:
public class programmer : person
{
Next we need to provide the constructors Here we specify the same constructors as the base class, and use the same inheritance syntax (the :) to indicate that this method inherits its implementation from the base class Any parameters should be passed to the base class constructor
public programmer(): base()
Trang 9To declare an additional constructor we follow the same rules, invoking the base constructor, but also providing additional functionality:
public programmer(string firstName, string lastName, int hoursSleep):
base(firstName, lastName)
{
_avgHoursSleepPerNight = hoursSleep;
}
And finally we have the new property:
public int AvgHoursSleepPerNight
{
get { return _avgHoursSleepPerNight; }
set { _avgHoursSleepPerNight = value; }
Interfaces work the same as in Visual Basic NET, providing an immutable contract to the external world
To create an interface, we use the interface construct For example:
Trang 10public interface IPerson
{
string FirstName(get; set;)
string LastName(get; set;)
string FullName();
}
To derive a class from an interface, we use the same method as inheritance:
public class Person : IPerson
{
private string _firstName;
private string _lastName;
public string FirstName()
Trang 11It's also possible to alias references using the following syntax:
using aliasName = Namespace;
If an alias is used, the alias must be included in references to classes that the namespace contains For example, if we have a namespace called MyComponent containing a class called MyClass, and import the namespace like this:
using foo = MyComponent;
we can't then access the class like this:
MyClass comp = MyClass
Trang 12We have to use this syntax:
foo.MyClass comp = foo.MyClass
Trang 13{
' code that always runs, whether or not
' an exception was caught
}
For example:
try
{
// connect to a database and
// retrieve some data
// code left out for clarity
Trang 14One really great feature that C# has over Visual Basic is the ability to include inline documentation This is done by placing
a set of XML tags at various places in our code, and then adding a compiler directive to pull out the comments For
Trang 15///The <c>programmer</c>class defines the salient
///attributes of every fine programmer
///<seealso cref="person">Inherits from person</seealso>
///<summary>Constructor using first and last names</summary>
///<param name="firstName">The first name of the programmer</param>
///<param name="lastName">The last name of the programmer</param>
Trang 16///<seealso cref="string"/>
public programmer(string firstName, string lastName):
base(firstName, lastName)
{ }
///<summary>Constructor using first and last names and
///the hours of sleep</summary>
///<param name="firstName">The first name of the programmer</param>
///<param name="lastName">The last name of the programmer</param>
///<param name="hoursSleep">The average number of hours of sleep</param>
///<value>Defines the average number of hours of sleep.</value>
public int AvgHoursSleepPerNight
Trang 17{
get { return _avgHoursSleepPerNight; }
set { _avgHoursSleepPerNight = value; }
c Text that indicates inline code
code Multiple lines of code, such as a sample
example Description of a code sample
exception Indicates an exception class Additionally, the attribute cref can be used to reference another type (such as
the exception type) This reference is checked against the imported libraries
include Allows XML documentation to be retrieved from another file
list
Indicates a list of items The type attribute can be one of:bullet, for bulleted listsnumber, for numbered liststable, for a tableYou can use a listheader element to define headings, and an item element to define the items in the list Each of these can contain two elements: item for the item being listed, and description
para Allows paragraph definitions within other tags
param Describes the parameter of a method The name attribute should match the name of the parameter Table continued on following page
paramref Used to indicate references for parameters
permission Describes the permissions required to access the member The cref can be used to reference another type
(such as the security permission type) This reference is checked against the imported libraries
remarks Overview information about the class or type
returns The return value of a method
Trang 18see The attribute cref is used to reference another type (such as a related member) This reference is checked
against the imported libraries
seealso The attribute cref is used to reference another type (such as a related member), to be documented in the
See Also section This reference is checked against the imported libraries
summary Description of a member or type
value Description of a property
In Visual Studio, these tags can be processed to form HTML pages that become part of the project documentation Outside Visual Studio, we can produce an XML file for the comments by using the /doc compiler switch (more on these later), which produces the file like so:
The <c>programmer</c>class defines the salient
attributes of every fine programmer
<seealso cref="T:peopleCS.person">Inherits from person</seealso>
</remarks>
</member>
Trang 19<member name="M:peopleCS.programmer.#ctor">
<summary>Default constructor</summary>
</member>
<member name="M:peopleCS.programmer.#ctor(System.String,System.String)">
<summary>Constructor using first and last names</summary>
<param name="firstName">The first name of the programmer</param>
<param name="lastName">The last name of the programmer</param>
<seealso cref="T:System.String"/>
</member>
<member name="M:peopleCS.programmer.#ctor(System.String, System.String,System.Int32)">
<summary>Constructor using first and last
names and the hours of sleep</summary>
<param name="firstName">The first name of the programmer</param>
<param name="lastName">The last name of the programmer</param>
<param name="hoursSleep">The average number of hours of sleep</param>
<seealso cref="T:System.String"/>
<seealso cref="T:System.Int32"/>
</member>
Trang 20P Property (including indexers)
M Method (including constructors)
E Event
! Error string if links cannot be resolved You could then use an XSLT stylesheet, or XML processing code to style this into your own documentation You could also add your own XML elements to the class descriptions, and these would be extracted along with the predefined elements
Unsafe Code
Although C# is part of the managed code environment, Microsoft has realized that sometimes developers need total control, such as when performance is an issue, when dealing with binary structures, or for some advanced COM support Under these circumstances, we are able to use C# code in an unsafe manner, where we can use pointers, unsafe casts, and so on
As an ASP.NET developer it's unlikely you'll ever need this, but knowing it's available gives us the flexibility to choose,
should the need arise Consult the C# documentation or Wrox's Professional C# Programming, ISBN 1-86007-04-3
for more information on this
Operator Overloading
C# is the only one of the supplied languages that supports operator overloading This works in the same way as method
Trang 21overloading, but for operators The reason for this is to allow the standard operators to be used on objects such as classes
The classic example given is a class for handling complex numbers, which have a real and imaginary part (stored as integers) Imagine a class that has two properties for these two parts, and a constructor that takes two arguments to match the properties:
CNumber c1 = new CNumber(12, 4);
CNumber c2 = new CNumber(5, 6);
When performing addition on complex numbers, we must add the real part and imaginary part independently of each other, and might consider creating this method:
public CNumber Add(CNumber c1, CNumber c2)
To achieve this, we would have to overload the + operator:
public static CNumber operator +(CNumber c1, CNumber c2);
{
Trang 22return new CNumber(c1.real + c2.real, c1.imag + c2.imag);
Although completely rewritten, JScript NET is more evolutionary, and still supports existing JScript functionality - the new features are extra, and (apart from compilation, which is a CLR requirement) not enforced
Like C#, JScript NET is case sensitive
Trang 23}
The compiler infers the type for idx from its usage This doesn't really change from the way the script engine runs with previous versions of JScript, except that now it's the compiler that does the work
Data Types
If we want to use data types, then we use a colon (:) to specify the type The new syntax is:
var name : type[[]] [ = value ]
For example:
var firstName : String // JScript String
var dateOfBirth : Date // JScript Date
var lastName : System.String // NET Framework string
var names : String[] // array of JScript Strings
Notice that both JScript and NET types are supported
Trang 24expando The class supports dynamic properties, and is given a default indexed property
public The class is publicly accessible
internal The class is only visible within the package in which it is declared Equivalent to Friend in Visual Basic and
internal in C#
abstract This class is an abstract class, and the class members must be implemented by inheriting classes Equivalent
to MustInherit in Visual Basic
final This class cannot be inherited Equivalent to NotInheritable in Visual Basic and sealed in C#
Trang 25[attributes] function memberName([parameters]) [: type]
{
}
The attributes can be one or more of the following:
Attribute Description
override The member overrides an identically named member from a base class
hide The member does not override an identically named member from a base class
Modifier Description
public The class is publicly accessible
internal The member is only visible within the package in which it is declared Equivalent to Friend in Visual Basic
and internal in C#
protected The member is only accessible from the containing class or types derived from the containing member private The member is only accessible from within the containing member
static The member is shared by all instances of the class, and exists independently of a class instance Equivalent
to Shared in Visual Basic
abstract This member is an abstract member, and must be implemented by inheriting classes Equivalent to
MustInherit in Visual Basic
final This method cannot be overridden, although it can be hidden or overloaded
Trang 26public var Op1 : double;
public var Op2 : double;
public function Add() : double
{
return Op1 + Op2;
}
}
The alternative, and preferred approach, is to use property accessors For example:
public class calculator
{
private var _op1 : double;
private var _op2 : double;
Trang 27public function get Operand1() : double
Trang 28Constructors
Like C#, the JScript NET syntax for class constructors is to use a method with the same name as the class For example:
public class person
{
private var _firstName : string;
private var _lastName : string;
public function person() {}
public function person(firstName : string, lastName : string)
Trang 29JScript NET uses the extends keyword to inherit from classes For example:
public class programmer extends person
{
private var _avgHoursSleepPerNight : int;
public function programmer()
Trang 30public function get AvgHoursSleepPerNight() : int
The class definition defines that our class is called programmer and the base class is called person:
public class programmer extends person
Next, we need to provide the constructors Here we specify the same constructors as the base class, and use the super keyword (meaning superclass) to call the method of the base class Any parameters are passed to the base class constructor:
public function programmer()
{
super();
}