widged.com
 

C# :: Language Overview

Hello World

 using System; 
 class Hello
 {
    static void Main() {
       Console.WriteLine("Hello world");
    }
 }

Program Structure

* Namespaces

  • Contain types and other namespaces
  • Type declarations
  • Classes, structs, interfaces, enums, and delegates
  • Members
  • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors
  • Organization
  • No header files, code written “in-line”
  • No declaration order dependence

Type System

  • Value types
    • Directly contain data
    • Cannot be null
      • Primitives int i;
      • Enums enum State { Off, On }
      • Structs struct Point { int x, y; }
  • Reference types
    • Contain references to objects
    • May be null
      • Classes class Foo: Bar, IFoo {…}
      • Interfaces interface IFoo: IBar {…}
      • Arrays string[] a = new string[10];
      • Delegates delegate void Empty();
  • C# predefined types
    • Reference object, string
    • Signed sbyte, short, int, long
    • Unsigned byte, ushort, uint, ulong
    • Character char
    • Floating-point float, double, decimal
    • Logical bool
  • Predefined types are simply aliases for system-provided types
    • For example, int == System.Int32

Classes

* Single inheritance

  • Multiple interface implementation
  • Class members
    • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors
    • Static and instance members
    • Nested types

Member access

  • public, protected, internal, private

Structs

* Like classes, except

  • Stored in-line, not heap allocated
  • Assignment copies data, not reference
  • No inheritance
  • Ideal for light weight objects
  • Complex, point, rectangle, color
  • int, float, double, etc., are all structs
  • Benefits
  • No heap allocation, less GC pressure
  • More efficient use of memory

Interfaces

  • Multiple inheritance
  • Can contain methods, properties, indexers, and events
  • Private interface implementations

interface IDataBound

 {
    void Bind(IDataBinder binder);
 } 
 class EditBox: Control, IDataBound
 {
    void IDataBound.Bind(IDataBinder binder) {...}
 }

Enums

* Strongly typed

  • No implicit conversions to/from int
  • Operators: +, -, ++, –, &, |, ^, ~
  • Can specify underlying type
  • Byte, short, int, long

enum Color: byte

 {
    Red   = 1,
    Green = 2,
    Blue  = 4,
    Black = 0,
    White = Red | Green | Blue,
 }

Delegates

* Object oriented function pointers

  • Multiple receivers
    • Each delegate has an invocation list
    • Thread-safe + and - operations
  • Foundation for events

delegate void MouseEvent(int x, int y);

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

Classes

public class Ade:base-class {} 
Ade a = new Ade();

Access Modifiers

  • public : no restrictions
  • private : only accessible to class
  • protected : only accessible to class and subclasses
  • internal : accessible to any class in assembly
  • protected internal : == protected or internal

Methods

return-type Name(params) {}

Constructors

Same name as class and no return type. Can have multiple constructors with different param lists.

Copy constructor must be created manually by passing an object in to a constructor method.

A static constructor will run before any instance of the class is created

Destructor

  • Should only be used if there are unmanaged resources
  • Called by garbage collector
~ClassName() {}

Dispose

  • Can define a Dispose method – implement interface IDisposable.
  • Should suppress GC using GC.SuppressFinalize(this);
  • Called automatically in using clauses eg using (x = new XYZ())
  • { } Dispose called automatically.

Within class reference

  • this is the current object
  • base is the super class object

Static members

  • Belong to and referenced by the class name
  • Cannot be referenced using an object instance

Params – by reference/by value

  • Default is by value for value types
  • Use (ref int x) to pass by reference
  • values must be assigned a value before use. If not initially assigned then use out: (out int x)

Overloading methods

  • Must change types or number of parameters – just changing return type doesn’t work.

Properties

  • Make instance variables private – access is via properties
public int Xyz { 
  get { return Xyz; }
  set { Xyz = value } 
} 
  • get or set are optional Can then use property as if it were a normal variable.
a.Xyz++

Inheritance

  • To override a base class method
  • base class must define method as virtual
  • public virtual void open()
  • to override it in child class public override void open()
  • All methods are final by default.
  • Helps in versioning, eg add a new method in base class that has already been declared in a subclass.
  • If method in subclass is the same as a virtual base method must use new to indicate it is not an override
eg public new virtual Xyz() 
  • Use sealed keyword to make a class final so it can’t be inherited

Abstract class/method

  • abstract public void Add();
  • Must be overriden by sub class.
  • Base class must also be abstract
abstract public class AdeBase { }

System.Object

  • Provides Equals(), GetHashCode(), GetType(), ToString(), Finalize(), MemberwiseClone(), ReferenceEquals()

Boxing/Unboxing

  • Boxing converts a value type to a reference type and is automatic
int I =123; i.ToString(); 
  • Unboxing converts from object to a value type – must be explicit
int I = 123; 
Object o = i; 
int j = (int)o;

Nesting classes

  • Can create private classes within a class. Use internal keyword. Similar to java static inner classes. If class is defined as public then it must be referenced using outer class
Outer.Inner.blah().

Operator Overloading

  • Defined as static methods, eg for a class Fraction to override + public static Fraction operator+(Fraction lhs, Fraction rhs) {}
  • [Convention is to use lhs and rhs]
  • Not all languages in .NET will support operator overloading and thus will not use these methods – worth adding separate add() method.
  • Be careful – make use intuitive.
  • If overloading ==, must also overload !=, same with >, < etc. Should also override Equals if overloading ==

Conversion operators

  • Can overload how compiler will convert between types when casting
Fraction f = 1.67; myInt = (int)f; 
use public static implicit operator Fraction (int theInt) { }

Structs

  • A simple user defined type, a lightweight alternative to a class. Can contain methods, properties etc. Doesn’t support inheritance. Does support multiple interfaces. A struct is a value type.
  • Useful in arrays, but not in collections as boxing is required.
  • Define similar to class:
public struct Ade {
  public SomeMethod() {}
} 
  • Create using new operator (although do’t have to!).
Ade x = new Ade();

Interfaces

  • By convention, the class name starts with I.
public interface IAde:baseclass {
  void Read(); 
  int Status{ get; set; }
} 
  • No access modifiers for methods/properties;
  • Interfaces can also implement other interfaces.
  • Can cast an object to the interface to use the interface, or use methods directly
Document doc = new Document(“ade”); 
IAde iaDoc = doc as IAde;
or IAde iaDoc = (IAde)doc; 
iaDoc.Read(); 
doc.Read();
  • Can test interface using is:
if (doc is IAde) {} 
  • The as operator returns null (rather than an error) if cast fails.
  • In a class implementing the interface, can put interface name as part of method declaration. Useful if two interfaces have same method name.
  • If explicit implentation then method is only visible when object is cast to the interface.
void IAde.Read() { } [Note – no access modifier] 
  • This allows implemented interface to be hidden if required.

Arrays

  • Arrays are objects and thus have a stack of methods available eg Copy, Sort, BinarySearch
int [] myArray; 
myArray = new int[5]; [First element is 0]
  • Array of value types are value types – not boxed objects. Button[] myArray = new Button[3]; - does not create objects only null references – still have create and assign button objects.
  • Access element using [index], eg myArray[3]
  • Multi-dimensional arrays, inc initialisation

int [,] x = new int[2,2];

  • Initialisation
int [,] x = { {1,2}, {3,4} } 
  • Jagged arrays – an array of arrays
int [][] x 
  • Arrays can be converted if type of the arrays can be converted

Params array

  • Can pass in multiple parameters to a method using a params array:
void MyMethod(params int[i] intVals) 
MyMethod(1,2,3); or MyMethod(myIntArray);

Indexers

  • Allows access to a class as if it were an array.
  • Effectively overloads the [] operator.
  • Declare an indexer within a class as: returnType this [accessType argument] { get; set;}
public string this[int i]
{ 
  get { };
  set { };
} 
  • then can access as obj[10] where obj is an instance of the class.
  • The accessType can be any type does not have to be an int. Can also overload using different accessTypes (eg an int and a String indexer)

Collections

  • Collections Interfaces: Various interfaces that classes can support to provide collection functionality
    • IEnumerable: allows support of foreach
    • ICollection: provide copy, count etc
    • IComparer: allows collection sorting
  • Collection Types
    • Array: as above
    • ArrayList: A dynamically sized array. Use Add, Remove etc
    • Queue: fifo collection. Use enqueue, dequeue, peek
    • Stack: lifo collection. Use pop, push, peek

Dictionaries

  • Associates values with a key. Any kind of object can be associated with any type of key.
  • Hashtable: Item, Add, Contains, Remove
  • IDictionary: interface to implement

Strings

  • string x = “abc”; or string x = @”abc”; # says treat string literally (ignore escape characters)
  • string intStr = myInt.ToString();
  • Available methods: eg Copy, Compare, Format, SubString, ToUpper, Trim, Split (breaks into substrings)
  • StringBuilder class for dynamically building and processing strings. Methods available: Append, Insert, Remove, Replace.

Exception Handling

  • throw new System.Exception(“…”);
try { } 
catch { } or catch (Exception type) { } 
finally { } 
  • System.Exception provides Message(), StackTrace(), InnerException(), TargetSite()
  • Custom exceptions must derive from System.ApplicationException
  • InnerException allows Exception to be saved as part of throwing a new
  • Exception – these can be nested.
  • Re-throwing exceptions: throw; or throw Exception;

Delegates and Events

  • A delegate is a reference type used to encapsulate a method with a particular signature.
public delegate int MyDelegate(params); 
  • Declare a method that uses delegate
public void Sort(MyDelegate delFunc) { 
  x = delFunc(params);
}

XML Documentation

  • Generate XML doc from code using /doc compiler switch
  • Reads comments marked with / Use tags such as <summary>, <returns>, <param> /<summary>This class does this<summary>
 
en/computers/lg/csharp/language-overview.txt · Last modified: 2009/12/06 21:33 by marielle
 
RSS - Banner by widged, template © 7throot HeadQuarters, 2007