1. Lexical Syntax
-------------- compiler csc -----------------
|C# src code |---------------->| MSIL exe or dll |
-------------- ------------------
execn + |
type verifn |
------------------
| JIT Compiler |
------------------
compiled to |
|
CLR -----------------------
final o/p <--------------| Managed Native Code |
-----------------------
int i = 100000; short s; s = (short)i; -> i = -31072; since max val breached
- BCL (base class lib) auto included in every prog
garb.coll = auto mem mgt scheme - priority increased when mem low -> free mem - Dispose() - explicitly free resrc
a. Cmd Line
static void Main() static void Main(String[] args) static int Main() static int Main(String[] args)Comments: // /* ... */ /// single line documentn /** multiline docu docu extracted at compile t to xml identifiers - muststart with letter/_, $ allowed by Java not allowed in c# - rest = alphanumeric - keywords allowed as identifiers if preceded with @, eg. public class @class - any nu of public + nonpublic classes canbe in single src f - src f name indepdt of contained classes - if 1+ Main(), /main flag must spec entry point
x. Security
4. Debugging (Trace + Debug; try-catch-finally)
x. WinForms
oHelpProvider = new HelpProvider(); oHelpProvider.SetShowHelp(oTextBox, true); oHelpProvider.SetHelpString(oTextBox, "Enter the street address in this text box.");
System.Web.UI > ControlCollection Class
FormStartPosition = Manual | CenterScreen | WindowsDefaultLocation | WindowsDefaultBounds |
CenterParent (use Location, center, deflt, deflt loc + deflt boundg size + centered on parent form)
MyForm.BackColor = System.Drawing.Color.Red;
MyForm.BackColor | ForeColor
MyForm.Font
MyForn.Text
MyForm.Cursor
.BackGroundImage
Opacity = 1 (deflt, fully opaque)
TabIndex
- PictureBox cannot recv focus -> no TabIndex prop
Anchor
Dock
System.Windows.Forms.Form: superclass of forms
Form.Show() - disply + recv focus, sets MyForm.Visible = true
ShowDialog() - show only after user complets actn,
Activate() - focus to visible form + move to front
Hide() - set MyForm.Visible = false
Close() - rem from memy
- cause form to remain open:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true
}
prevent KeyPress evt handler exec:
private void MyForm_KeyPress(object sender, KeyPressEventArgs e) {
e.Hanlded = true;
}
aControl.Focus(); (give focus)
- Beep() exists in vb.net not cs
- ErrorProvider:
1. oControl.CausesValidation = true;
2. f_validating { ... oErrorProvider.SetError( oTextBox, "no blanks"); }
myCheckBox.AccessibleName = "Preview";
myCheckBox.AccessibleDescription =
"A toggle button used to show the document preview.";
+ When the mouse enters the control to be dropped, the DragEnter
event is fired.
+ When the mouse hovers over the control to be dropped, the DragOver
event is fired.
+ When the mouse leaves the control to be dropped, the DragLeave
event is fired.
+ When the mouse drops over the control to be dropped, the DragDrop
event is fired.ListBox1_DragEnter
Container Ctrls: - Panel: scrollable cont no captn Panel.AutoScroll = true; (enable scroolbars in panel) - GroupBox - TabControl TabControl.TabPages - GroupBox - GroupBox.Enabled = false - Controls Collectn: all ctrls contained by container ctrl: Control oControl = oForm.Controls[3]; oForm.Controls.Add(oLabel); oForm.Controls.Remove(oLabel); oForm.Controls.RemoveAt(3); oControl.TabPages[1].Controls.Add(oButton); - Button.Click - Button: deflt evt: Click - Checkbox.CheckChanged: deflt evt .Click .DoubleClick MouseEnter MouseMove MouseHover MouseDown MouseWheel MouseUp MouseLeave MouseEventArgs - Button, Clicks (no. clicks) Delta (no notches wheel rotated, +/-, 1 notch=120) - ToolTipProvider string s_tooltip = oToolTipProvider.GetToolTip(oButton); oToolTipProvider.SetToolTip(oButton, "hi"); Menus: MainMenu ShowShortcut = true | false oMenuItem.Checked = true; oMenuItem.Visible = false; oContextMenu.MenuItems.Add( oMenuItem.CloneMenu() ); oMenuItem.MergeMenu( oContextMenu ); TextBox.MexLength | PasswordChar | ReadOnly | MultiLine Keybd events: KeyDown | KeyPress | KeyUp KeyEventArgs KeyUp, KeyDown if Alt, Ctrl, Shift fires KeyEventArgs, KeyEventArgs.Alt | Ctrl | Shift = true ( Alt key pressed) KeyEventArgs.KeyCode - gives Key val of key, e.KeyCode.ToString(); KeyPress (if key has ascii val), KeyPressEventArgs raised, KeyPressEventArgs.KeyChar gives ascii val Char.IsDigit(eKeyPressEventArgs.KeyChar) == true | IsLetter | IsLetterOrDigit | IsPunctuation | IsLower | IsUpper if(oTextBox.CanFocus == true) oTextBox.Focus();
j2se: java.net - System.Net collections - System.Collections jaxp (java api for xml processg) - System.Xml rmi - remoting jdbc - ado.net jndi - System.DirectoryServices awt/swing - Winforms java2d - gdi+ javabeans - - corba - - j2ee: ejb - - javamail - System.Web.Mail jca (java connector arch.) - ms Host Integratn Server jms (java message service) - MSMQ (Ms Msg Queuing) jsp - asp.net jta (java transaction api) - MTS (Ms. Transactn Server) servlets - jspSyntax
KEYWORDS (Jones 2003, p.41f)
c# - java
using = import
namespace = package
Types + Constant Keywords: Simple Types
Integer Types
-------------
cs : type : java : desc
bool : System.Boolean: boolean : true | false
char : System.Char : char : (16b unicode char)
sbyte : System.SByte : byte : (8b signed int -128-127)
byte : System.Byte : - : (8b unsigned int 0-255)
short : System.Int16 : short : (16b signed int -32768-32767)
ushort : System.UInt16 : - : (16b unsigned int 0-65535)
int : System.Int32 : int : (32b signed int -2x109-2x109
uint : System.UInt32 : - : (32b unsigned int 0 - 4x109)
long : System.Int64 : long : (64b signed int)
ulong : System.UInt64 : - : (64-bit unsigned int 0 - 1.8x1019 | 264-1)
string : System.String :
object : System.Object : supertype of all types
true | false | null | void : true | false | null | void
(true,false,null are not java keywords but literals)
Floating Point Types
--------------------
float : System.Single : float : (32b double precisn floatg pt)
double : System.Double : double : (64b double precisn floatg pt, approx. 10-324 - 10308)
decimal : System.Decimal: - : (128-bit hi-prec dec with 28 significt digits for financial calcs)
Complex Type
------------
class : class
const : const
delegate: - (ref type defing method signature)
enum : - (set of named constts)
event : - (event member)
this : - (indexer member in class/struct)
interface: interface
object : - (alias for System.Object, java Object class not keyword)
operator: -
string : - (alias for System.String for Unicode String vals, java String not keyword)
struct : - (complex type)
- : extends (c#: class : superclass {...} )
- : implements (c#: class : interface {...})
params : - (id a param array)
out : - (var not require init tobe passed to fu, java out i/o)
ref : - (id var by reference not by value)
as : - (cast but return null if cast fails, no exceptn)
is : instanceof (is obj an instance of type)
new : new (mk instance of type)
typeof : - (return instance of System.Type for spec type)
base : super (ref.superclass members)
this : this (self-ref)
explicit: - (declare explicit type conversn operator)
implicit: - (declare implicit type conversn operator)
Access Modifier Keywords
public : public (var:public | class: instantiated byany obj, deflt for class/struct)
private : private (var: onlyfor members of class | instant by objs of own type or ext nested classes)
protected: protected (class + subclasses; c# protected different from java)
internal: - (all members of assembly | instant only be mems of assembly)
protected internal: - (union of prot + int, assembly or subclasses)
Inheritance Keywords
abstract: abstract (incomplete implementn of prog elemt)
sealed : final (cannot be derived from)
new : - (hides inherited member, deflt, != new for obj instantiatn)
override: - (overrides inherited virtual member with same sig, only virtual
mems canbe overridden)
virtual : - (canbe overridden in subclass, deflt for java)
Other Modifier Keywords
readonly: final (field assignable only once)
extern : native (implementn external to c# code, usu dll)
static : static (static elemt existg in context of type not of class/struct instance)
- : strictfp
lock : synchronized (synchronized access to block not full fu unlike synch)
- : transient (c# NonSerialized comparable)
volatile: volatile (synchronized + ordered field access)
Flow Control Keywords
- : assert (c#: Trace + Debug)
if : if
else : else
switch : switch
case : case
default : default
for : for (determinant loop)
do : do (postloop conditnal)
while : while (preloop conditnal)
foreach : -
in : - (part of foreach)
goto : goto (unused reserved keywords java, cs: unconditnal branchg)
continue: continue (start new loop iteratn)
break : break
return : return
Exception Handling Keywords
try : try
catch : catch
finally : finally
throw : throw (throw/rethrow exceptn)
- : throws
checked : - (arithmetic overflow checkg on, oper + stmt)
unchecked: - (arithmetic overflow checkg off)
Unmanaged Code Keywords
fixed : - (allow pointer to ref managed var -> garbace collector not deallocate var in use)
sizeof : - (siz ein bytes of memory occupd by avlue type instance)
stackalloc: - (alloc mem blocks on stack for storage of local vars)
unsafe : - (unsafe members)
Operator Keywords
c# java
is instanceof
sizeof - (bytes occupd by value type in mem, only in unsafe)
typeof Class.forName (get System.Type obj)
checked unchecked - (overflow excepn ctrl)
* -> [] & - (indirn + addr operators)
- > > > , > > > =
+ - - (delegated concatn removal)
true|false - (operators aswellas literals)
- abstract, sealed are mutex - structs cannot be abstract as they dont support inheritance - all abstract mems implicitly virtual - abstract mutex with static, virtual + override - abstract fu's must have empty stmt - subclass fu providg implementn of abstract fu musthave override keyword - new + override mutex - overridg mem mustbe delcared with same accessibility modifiers as overridden fu - override mutex with new, static, virtual, abstract - mem being overridden mustbe accessible to overridg mem - warng if atempt to override nonvirtual mem - sealed + abstract mutex - structs implicitly sealed + dont support inheritance - sealed + override on inherited virtual fu -> fu cannot be overridden by subclasses - sealed class -> cannot be subclassed - virtual mutex with static, abstract + override - if extern implement in dll, mems mustbe static + use DLLImport attrib - extern mutex with abstract - body of mem modifd with extern mustbe empty - static fus have no access to this
namespaces
- nested ns: cannot use hierarchical name in single declarn, ie
namespace ns1 { namespace ns2 { namespace ns3 ... not namespace ns1 { namespace ns1.ns2
- if no namespace defd, mems of deflt global ns + no ns requd for access
- ns implicitly public accessibility
- using = import
- 1 mem cannot be imported by using unlike java
using MyNamespace {
using co = com.mycompany; // alias for ns
c# java
goto mylabel ... break mylabel ...
mylabel: ... mylabel: ...
CONTROL FLOW
- cs not support fall-through for case
- goto case "red"; (switch)
- compiler error if goto called in finally
- break : exit enclosg stmt
- continue: start new iteratn of enclosg stmt
string[] s = new string[] {"a", "be", "cee"};
- System.OverflowException if val of checked expr cannot be found till runtime
- unchecked deflt for vars.
- checked deflt for constants
- using ( MyClass c = new MyClass(), MyStruct s = new MyStruct() ) { c.f(); s.f(); ... }
if MyClass, MyStruct implement System.IDisposable
}
b. OOPs
c. Data Structures
- value types (java: "primitive types") : byte, int, long, float, double
- reference types: class, interface, array, pointer
- every data type subclass of System.Object
- boxing: auto convert value type to reference type if val type used as object or cast to interface
= java wrapper classes
eg. object xobject = xint; object xobject = 45L;
IInterface i = oMyStruct; if MyStruct implements IInterface
- unboxing
int xint = (int) xobject;
else System.InvalidCastException
- struct like class, but structs removed when scope lost,
public struct MyStruct : IMyInterface { ... }
- structs <-- System.ValueType <-- System.Object
- empty constructors valid for classes, invalid for structs as deflt constructor sets all mems
to deflt vals
- new keyword not requd for instantiatn of structs but then all mems mustbe explicitly
assigned else compiler error
- struct vars cannever be assigned null
- structs cannot have destructors as structs are not garbage collected
- ref or out requd to pass struct by reference, else passed by value + local copy made
- small: structs, large data struct: use class
- structs faster as stack-based
c. Preprocessor
* #if
* #else
* #elif
* #endif
* #define
* #undef
* #warning
* #error
* #line
* #region
* #endregion
d. XML Documentation
3. GDI+
SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true);
| SolidBrush | simplest brush, paintg in solid color. |
| HatchBrush | paints in large no. preset patterns |
| TextureBrush | paints usg texture, eg. an img |
| LinearGradientBrush | 2 colors blended alg gradient. |
| PathGradientBrush | complex gradt of blended colors along defined unique path. |
4. Threading Thread = basic unit to which processor allocates processor time
if(t.ThreadState == ThreadState.Running)
{ t.Suspend(); }
if(t.ThreadState == ThreadState.Suspended)
{ t.Resume(); }
| Member of ThreadState enum | Description |
|---|---|
| Aborted | The thread is in the Stopped state. |
| AbortRequested | The ThreadAbort method has been invoked on the thread, but the thread has not yet received the pending System.Threading.ThreadAbortException that will attempt to terminate it. |
| Background | The thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the IsBackground property of the Thread class. |
| Running | The thread has been started, it is not blocked, and there is no pending ThreadAbortException. |
| Stopped | The thread has stopped. |
| StopRequested | The thread is being requested to stop. This is for internal use only. |
| Suspended | The thread has been suspended. |
| SuspendRequested | The thread is being requested to suspend. |
| Unstarted | The Thread.Start method has not been invoked on the thread. |
| WaitSleepJoin | The thread is blocked as a result of a call to Wait, Sleep or Join methods. |
4. Collections
oTextBox.Text = "hello";
private string slocal;
public string s
{
get{ return slocal; }
set{ if(...)... slocal = value; }
}
- value = val of property being set
readonly props
private readonly int i;
public int xint { get{ return i; } }
- indexer: deflt property, name = this:
public int this[int i] {...}
public delegate void oDelegate(double d); // delegate evt will use public event oDelegate MyEvent; ... MyEvent(2); // raise evt
- evt handler = fu called through delegate when evt raised - if evt withno evt handler raised -> error - instance evts + shared/static evts - evt handlers can return value - Evt Handler - System.EventHandler = deflt delegate class for most WinForms ctrls.
oButton.Click += new System.EventHandler( clickHandler ); oObject += new oDelegate(f); // assoc evt with delegate oObject -= new oDelegate(f); // remove handler at runtime
5. Windows Forms
x. Visual Studio vs.net
public void f_keydown(Object o, KeyEventArgs e)
{
if(e.KeyCode == Keys.Down) { f_down(); }
}
publc void f_keypress(Object o, KeyPressEventArgs e)
{
if(e.KeyChar == 'n') f_newgame(); // usg codes for down keys not work
if(e.KeyChar == (char)12) f_quit(); // use numeric key vals
}