IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
To/From Code
-Collapse +Expand Cross Ref Guide
-Collapse +Expand Members-Only
Sign in to see member-only pages.
   ► KBTo/From GuidesC#  Print This     

C# and JavaScript Cross Reference Guide

By Mike Prestwood

C# versus JavaScript: A side by side comparison between C# and JavaScript.

C#

Version: This content is based on Microsoft C# 2008 and were tested in Microsoft Visual Studio.Net 2008. 

This content focuses on topics in common among the languages documented here so some of this syntax will look similar to C++ and Java but there are significant differences.

Note: To be clear, the subject of this information is the version of C# used by Visual Studio.Net. It does not address in any significant way C#Builder by CodeGear. Although much of the information also applies to C#Builder, all of it applies to the latest version of Visual C#.

JavaScript

Version: This content is based on JavaScript 1.5 and tested using our web hosting server farm with several browsers including IE, FireFox, and Safari. The focus of this content is on browser-side scripting.

 
Tool Basics
 

Developer environment basics such as common file extensions, common keyboard shortcuts, etc.

Deployment Overview

[Other Languages] 
C#: 

C# projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.

In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).

In addition, C# projects also support ClickOnce which brings the ease of Web deployment to Windows Forms and console applications. To get started, right click on your solution in the Solution Explorer, click Properties then select the Security tab. 

In addition, you can use any of the many free and commercially available installation packages.

[Not specified yet. Coming...]




Development Tools

[Other Languages] 

Languages Focus

Primary development tool(s) used to develop and debug code.

C#: 

Microsoft Visual C# and the full version of Microsoft Visual Studio.Net are the current primary tools. CodeGear does have C#Builder but it's not a primary tool currently and development on the tool has slowed in recent years.

More Info / Comment
JavaScript: 

Many developers just use a text editor. There are JavaScript editors available including 1st JavaScript Editor, Antechinus JavaScript Editor Professional, and SplineTech JavaScript Debugger PRO.

More Info / Comment




File Extensions

[Other Languages] 

Languages Focus

Common or primary file extensions used (not a complete list, just the basics).

C#: 

Common source code file extensions include:

  • .SLN - Solution File. Contains solution specific information such as links to the projects within this solution.
  • .CSPROJ - C# Project File. Contains project specific information. When you add a file containing one or more classes, it is added to this file.
  • .CS - C# source file.
  • .Designer.CS - C# form file (a text resource file).
Syntax Example:
//Sample code snippet from the .csproj project file:
<ItemGroup>
  <Compile Include="Cyborg.cs" />
  <Compile Include="Cyborg600.cs" />
  <Compile Include="Form1.cs">
    <SubType>Form</SubType>
  </Compile>
  //...
JavaScript: 

.js is the common standard for browser-side JavaScript and .jsp is the common standard for server-side JavaScript.

More Info / Comment




Overview and History

[Other Languages] 
C#: 

Language Overview: C# is an OOP language (no global functions or variables) and is type-safe. You code using a fully OOP approach (everything is in a class).

Target Platforms: C# is most suitable for creating .Net Framework applications. This includes desktop business application using WinForms and websites using WebForms.

More Info / Comment
JavaScript: 

Language Overview: Class-like language with limited but usable class-like and object-like functionality but no formal inheritance nor visibility control, etc.

Many developers are hoping the next version of JavaScript will be a fully OOP language. If you're a working OO developer and need to use JavaScript in an OO manor now, there are many books that help you simulate OOP. One such book we recommend is Pro JavaScript Design Patterns.

Target Platforms: JavaScript is most commonly used to extend HTML by executing code on the browser side when visiting a website. It does have other uses including server side scripting and AJAX.

More Info / Comment




Report Tools Overview

[Other Languages] 

Languages Focus

Built-In: Some development tools have a reporting tool built-in and some do not. For example, typically desktop databases such as Paradox and Access have a built-in reporting tool and typically that reporting tool is used with nearly every application built with it. A built-in reporting tool makes development of reports across many clients and applications consistent and therefore easy.

Add-On: Development tools that do not have a built-in reporting tool need to use either a currently bundled report writer, or one of the popular reporting tools that integrates well with the development tool. For example, popular reporting tools include Crystal Reports, ReportBuilder, and MS SQL Reporting Services (tied to MS SQL).

C#: 

For WebForm applications the client target is the browser (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations).

For WinForm applications, Crystal Reports is still a popular choice with C# developers because it has been bundled with many Microsoft products, it's overall popularity, and compatibility with many different development tools.

JavaScript: 

No built-in report writer but because JavaScript most frequently targets website development (a document interfaced GUI), a common solution is to simply output an HTML formatted page with black text and a white background (not much control but it does work for some situations).

More Info / Comment




 
Language Basics
 

Language basics is kind of a catch all for absolute beginner stuff. The items (common names) I chose for language basics is a bit random and include items like case sensitivity, commenting, declaring variables, etc.

Case Sensitivity

[Other Languages] 

Languages Focus

Case sensitiviy in this case is referring to commands and variable names. For example, are "printf" and "PrintF" equivalent? Are fullname and FullName equivalent? When you create commands, operations, methods, or variables should you worry about case?

C#:   Yes

In C# commands and variable names are case sensitive. The following does NOT:

messagebox.Show("hello");  //Does not compile!

The first time you type any other case for commands or variables, VS.Net will change it to the accepted or defined case. For example, if you type messagebox.show it is converted to MessageBox.Show. Once corrected, you can break it again by editing MessageBox to messagebox and the compiler will give you an error.

Syntax Example:

The following code works:

MessageBox.Show("hello");
JavaScript:   Yes

JavaScript is case sensitive. Change the case, and it no longer works! Notice the "W" in "Write" is capitalized.

<script language=JavaScript> 
<!--
document.Write("Hello"); //Does not work!
//-->
</script>

Variable names are case sensitive.

Syntax Example:

This does work:

<script language=JavaScript> 
<!--
document.write("Hello");
//-->
</script>




Code Blocks

[Other Languages] 

Languages Focus

The rules for code blocks within a language dictate where you can declare variables, how you "bracket" code, etc.

C#:   { }

C# uses braces {} to indicate a code block of more than one line. For one line of code, the braces are optional.

I prefer to put the opening { and the closing } on their own line only because most of the examples I see do this. As opposed to C++, Java, and JavaScript where I put the opening bracket at the end of the first line (which I actually prefer).

Syntax Example:
int DoSomething()
{
 int a = 1;
 int b = 2;
 return a + b;
}
JavaScript:   { }

In html pages, you embed JavaScript code between <script> and </script> (see example). Also it's tradtional to put an HTML comment around your code too so that really old browsers don't crash (probably not all that important these days).

For JavaScript, Java, PHP, and C++, I prefer to put the first { at the end of the first line of the code block as in the example above because I see moreJavaScript codeformatted that way.

Syntax Example:
<script language="JavaScript" type="text/javascript">
<!--
function DisplayDialogLg(StrURL) {
}
if (x == -1) {
}
-->
</script>




Comments

[Other Languages] 

Languages Focus

Commenting code generally has three purposes: to document your code, for psuedo coding prior to coding, and to embed compiler directives. Most languages support both a single line comment and a multiple line comment. Some languages also use comments to give instructions to the compiler or interpreter.

C#:  "Multiple Line Comment" // or /* */

Commenting Code
C# uses "//" for a single line comment and /* */ for a multiple line comment.

Syntax Example:
//Single line comment.

/*
Multiple line
comment.
*/
JavaScript:   // or /* ... */

Commenting Code
JavaScript uses "//" for a single line comment and /* */ for a multiple line comment.

Syntax Example:
//This is a single line comment.

/*
Multiple line
comment.
*/




Constants

[Other Languages] 

General Info: Computer Language Constants

A constant is just like a variable (it holds a value) but, unlike a variable, you cannot change the value of a constant.

C#:   const

In C#, you define constants with the const keyword.

All constants are part of a class (no global constants) but you can make a constant public and have access to it using ClassName.ConstantName so long as you have added the class to the project. This works even without creating the class as if the public constants were static, but you cannot use the static keyword.

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Syntax Example:  
public class Convert : Object
{
  public const string kName = "Mike";
 
  //You can declare multiple of the same type too:
  const Double kFeetToMeter = 3.2808, kMeterToFeet = .3048;
}
JavaScript:   Not Supported

Although JavaScript has variables, it does not have constants.





End of Statement

[Other Languages] 

Languages Focus

In coding languages, common End of statement specifiers include a semicolon and return (others exist too). Also of concern when studying a language is can you put two statements on a single code line and can you break a single statement into two or more code lines.

C#:   ;

C# uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code if you wish as well as split a single statement into two or more code lines.

Syntax Example:  
Console.WriteLine("Hello1");
Console.WriteLine("Hello2");
Console.WriteLine("Hello3");

//Same line works too:
Console.WriteLine("Hello4"); Console.WriteLine("Hello5");
 
//Two or more lines works too: 
Console.
  WriteLine
("Hello6");

JavaScript:   ; is optional

In JavaScript, using a semicolon at the end of statements is optional. You might think a semicolon then is just another comment specifier but it is not. The semicolon is an optional end of statement specifier. To put two statements on a single code line, you must use a semicolon. However, the semicolon is optional, but probably confusing, when you break a single statement into multiple code lines.

Syntax Example:
document.write("Hello1");
document.write("Hello2");

//Semicolons are optional:
document.write("Hello3")
document.write("Hello4")

//This works too but only if you use a semicolon:
document.write("Hello5"); document.write("Hello6");

//Two lines also works:
document.write
("Hello7")




Literals

[Other Languages] 

General Info: Programming Literals

A value directly written into the source code of a computer program (as opposed to an identifier like a variable or constant). Literals cannot be changed. Common types of literals include string literals, floating point literals, integer literals, and hexidemal literals. Literal strings are usually either quoted (") or use an apostrophe (') which is often referred to as a single quote. Sometimes quotes are inaccurately referred to as double quotes.

Languages Focus

In addition to understanding whether to use a quote or apostrophe for string literals, you also want to know how to specify and work with other types of literals including floating point literals. Some compilers allow leading and trailing decimals (.1 + .1), while some require a leading or trailing 0 as in (0.1 + 0.1). Also, because floating point literals are difficult for compilers to represent accurately, you need to understand how the compiler handles them and how to use rounding and trimming commands correctly for the nature of the project your are coding.

C#:   quote

String literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \".

To specify a floating point literal between 1 and -1, you can preceed the decimal with a 0 or not (both work). In other words, preceding decimals are allowed (both .1 and 0.1). Trailing decimals are not allowed.

Syntax Example:
Console.WriteLine("Hello");
Console.WriteLine("Hello \"Mike\".");
 
//Does C# evaluate this simple
//floating point math correctly? No! 
if ((0.1 + 0.1 + 0.1) == 0.3)
{
MessageBox.Show("Correct");
}
else
{
MessageBox.Show("Not correct");
}
JavaScript:   quote or apostrophe

String literals use either an apostrophe (also known as a single quote) as in 'Prestwood' or quoted as in "Prestwood". If you need to embed an apostrophe in an apostrophe-literal or a quote in a quoted-literal, precede it with a slash as in \' and \".

Syntax Example:
Alert("Hello");
Alert("Hello \"Mike\".")
  
Alert('Hello');
Alert('Hello Mike\'s website.')
 
//Does JavaScript evaluate this simple
//floating point math correctly? No! 
if ((.1 + .1 + .1) == .3) {
 document.write("Correct")
} else {
 document.write("Not correct")
}




Variables

[Other Languages] 

Languages Focus

A variable holds a value that you can use and change throughout your code so long as the variable is within scope. With variable declaration, you not only want to know the syntax of how you declare a variable but you also want to know where. Are you allowed to declare a variable inline? What are the available scopes: local vs. global. Can you assign a value at the same time you declare a variable?

C#:   Int16 x=0;

C++, Java, and C# all use C-like variable declaration.

C# has C-like variable declaration and although variables are case sensitive, VS.Net will auto-fix your variable names to the defined case.

C# offers many variable types. Some common types used include short, intlong, float, double, decimal, Int16, UInt16, Int32, Int64, string, and bool.

You can also specify the value when you declare a variable as in:

String FirstName = "Mike";
String LastName = "Prestwood";
Int16 Age = 42;
Syntax Example:
string FullName;
int16 Age;
double Weight;
 
FullName = "Mike Prestwood";
Age = 32;
Weight = 154.4;
JavaScript:   var x = 0;

JavaScript is a loosely typed language. Each variable is cast in usage as string, number, boolean, function, or object.

Variable names are case sensitive.

Alternatively, you can specify the value when you declare a variable:

var FirstName = "Mike";
var LastName = "Prestwood";
var Age = 42;
Syntax Example:
var FirstName;
var LastName;
var Age;




 
Language Details
 

Language Details is kind of a catch all for stuff that didn't make it into language basics nor any other category.

Custom Routines

[Other Languages] 

Languages Focus

For non-OOP languages, a custom routine is a function, procedure, or subroutine and for pure OOP languages, a custom routine is a class method. Hybrid languages (both non-OOP and OOP) combine both.

C#: 

C# requires () in both the function declaration, and when it's invoked. Leave off the parens to signify a property.

ReturnType RoutineName()
Syntax Example:
void SayHello(String pName)
{
MessageBox.Show("Hello " + pName);
}
int Add(int a, int b) 
{
return a + b;
}
JavaScript:   function

JavaScript uses functions and loosely typed parameters. Function definitions must come before their usage so the usual preference when adding JavaScript to HTML pages is to include them between the head tags.

Syntax Example:
function SayHello(pName) {
 document.write("Hello " + pName + "<br>");
}
 
function add(p1, p2) {
 var result;
 
 result = p1 + p2;
 return result;
}




Event Handler

[Other Languages] 

In computer programming, an event handler is part of event driven programming where the events are created by the framework based on interpreting inputs. Each event allows you to add code to an application-level event generated by the underlying framework, typically GUI triggers such as a key press, mouse movement, action selection, and an expired timer. In addition, events can represent data changes, new data, etc. Specifically, an event handler is an asynchronous callback subroutine that handles inputs received in a program.

A custom event is a programmer created event. For example, you can contrast an event handler with a member event, an OOP concept where you add an event to a class.

Languages Focus

Many development environments and compilers provide for event driven programming, a standard set of application events such as startup, end, on click of a button, etc. This section documents the applicaton event handler or an overview for each language.

For OOP languages, do not confuse this section with class member events discussed in the OOP Details section of our Cross Reference Coding Encyclopedia.

[Not specified yet. Coming...]
JavaScript: 

The JavaScript event handler contains events centered around the Document Object Model (DOM). Common events include onMouseOver and onMouseOut, onFocus and onBlur, onClick and onDblClick, onChange and onSelect, onLoad and onUnload.

For example, onMouseOver and onMouseOut are frequently used with websites to change an image when your mouse moves over it. The onClick event is used to trigger code upon a mouse click.

Syntax Example:

In the following example, we use a standard image tag set to an image, change it on mouse over, then set it back on mouse out.

<img id="Image1" src="i_search.gif"
 onmouseover="document.images['Image1'].src='i_coat.gif';"
 onmouseout="document.images['Image1'].src='i_search.gif';">




Inline Code

[Other Languages] 

Languages Focus

Also known as embedded code where you embed another syntax language within the native code of the development environment you are using. The inline code can be compiled by the current development's compiler or by an external compiler.

Do not confuse with inlining which is a coding technique where custom routines are moved inline where the code is executed either by you, by a compiler directive, or automatically by the compiler.

C#:   Not Supported

Since all the .Net languages compile into intermediate language (IL), and not to a specific CPU, they do not provide support for inline assembler code.

[Not specified yet. Coming...]




Inlining

[Other Languages] 

General Info: Inline Routines

Instead of calling a routine, you move the code from the routine itself and expand it in place of the call. In addition to manual inlining, some languages support automatic inlining where the compiler or some other pre-compiler decides when to inline a code routine. Also, some languages allow for developer defined inlining where the developer can suggest and/or force the inlining of a code routine. Inlining can optimize your code for speed by saving a call and return, and parameter management.

Languages Focus

Does it support inlining? If so, does it support developer defined inlining? Does it support automatic inlining? Both?

C#:   Automatic

In C#, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.

More Info / Comment
JavaScript:   Not Supported




Overloading

[Other Languages] 

Types of overloading include method overloading and operator overloading.

Method Overloading is where different functions with the same name are invoked based on the data types of the parameters passed or the number of parameters. Method overloading is a type of polymorphism and is also known as Parametric Polymorphism.

Operater Overloading allows an operator to behave differently based on the types of values used. For example, in some languages the + operator is used both to add numbers and to concatenate strings. Custom operator overloading is sometimes referred to as ad-hoc polymorphism.

C#:   implicit

C# supports both method and operator overloading.

For methods, C# supports implicit overloading (no need for an overload keyword).

JavaScript: 

JavaScript Overloading

  • Operator - No.
  • Method -
Syntax Example:

 





Parameters

[Other Languages] 
C#: 

In C# the data type of each parameter must be specified, even if adjacent parameters are of the same type. To pass a parameter by reference, use the ref or out keyword.

Syntax Example:

integer Add(int a, int b)

[Not specified yet. Coming...]




Self Keyword

[Other Languages] 
C#:   this

To refer to the current instance of a class, use the this keyword. The this keyword provides a way to refer to the specific instance in which the code is currently executing. It is particularly useful for passing information about the currently executing instance.

The this keyword is also used as a modifier of the first parameter of an extension method.

You cannot use this with static method functions because static methods do not belong to an object instance. If you try, you'll get an error.

More Info / Comment
[Not specified yet. Coming...]




 
Data Structures
 

Data structures allow you to store and work with data. Common data structures include arrays, associative arrays, etc.

Associative Array

[Other Languages] 
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'

Languages Focus

Associative arrays are also known as a dictionary or a hash table in other languages.

C#:   Dictionary
Syntax Example:
//using System.Collections.Generic;
 
Dictionary <String, String> airports = new Dictionary <String, String>();
airports.Add("LAX", "Los Angeles"); 
airports.Add("SFO", "San Francisco");
airports.Add("SAN", "San Diego");
MessageBox.Show(airports["LAX"]);
JavaScript:   Array(), use [
Syntax Example:
var MyStateList= new Array()
MyStateList["CA"]="California";
MyStateList["OR"]="Oregon";
Alert("OR is " + MyStateList["OR"])




Pointers

[Other Languages] 

General Info: Pointers / References

A pointer is a variable type that allows you to refer indirectly to another object. Instead of holding data, a pointer holds the address to data -- the address of another variable or object. You can change the address value a pointer points to thus changing the variable or object the pointer is pointing to.

A reference is a type of pointer that cannot change and it must always point to a valid storage (no nulls).

C#: 

Although pointer data types in C# coding are less important than in other languages such as C++, C# does support developer defined pointers. Use the * operator to declare a pointer data type. Use the & operator to return the current address of a variable.

In .Net managed coding the use of pointers is not safe because the garbage collector may move memory around. To safely use pointers, use the unsafe keyword. However, avoid unsafe code if possible.

C++/CLI has more extensive support for pointers than C#. If you have needs that go beyond what C# offers, you can code in C++/CLI and add it to your project.

Syntax Example:
//Declare a pointer of type integer.
Integer *PCounter;
JavaScript:   Not Supported

JavaScript does not offer developer defined pointers. However, you can use the eval function to simulate pointers.





 
Statements
 

Common statements such as if statements, loops, etc.

Exception Trapping

[Other Languages] 

Languages Focus

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

C#:   try...catch...finally

C# uses a try...catch...finally statement to trap for errors.

try {}
catch {}
finally {}
Syntax Example:
try
{
int y = 0;
y = 1 / y;
}
catch
{
MessageBox.Show("you cannot divide by zero");
}
JavaScript:   try/catch/finally

See "throw" to raise (throw) an error.

Syntax Example:
try {
  //Do something.
}
catch(e) {        //one or more.
  //Do something.
}
finally {         //0 or one.
  //Do something.
}




If Statement

[Other Languages] 
C#:   if..else if..else

Use () around evaluation with no "then".

Syntax Example:
Boolean x = true;


if (x)
{
MessageBox.Show("hello");
}
else if (x==false)
{
MessageBox.Show("goodbye");
}
else
{
  MessageBox.Show("what?");
}
JavaScript:   if..else if..else

Same as C/C++ but, as usual, the semicolons are optional.

Syntax Example:
var x = 8;
  
if (x == 10) {
 document.write("x is 10.");
} else if (x < 10) {
 document.write("x is less than 10."); 
} else {
 document.write("x must be greater than 10.");
}




 
Operators
 

A language symbol used for assignment, comparison, computational, or as a logical.

Assignment

[Other Languages] 

Languages Focus

Common assignment operators for languages include =, ==, and :=. An assignment operator allows you to assign a value to a variable. The value can be a literal value like "Mike" or 42 or the value stored in another variable or returned by a function.

C#:   =

C# uses = for it's assignment operator.

Syntax Example:
int Age;
string FullName;
  
Age = 42;
FullName = "Randy Spitz";
JavaScript:   =

JavaScript uses = for it's assignment operator.

Syntax Example:
//Regular assignment.
LastName = 'Spitz';
  
//Variable declaration with assignment.
var FullName = 'Randy Spitz';
var Age = 38;




Comparison Operators

[Other Languages] 

General Info: Round Floating Point Numbers

When comparing floating point numbers, make sure you round to an acceptable level of rounding for the type of application you are using.

Languages Focus

A comparison operator compares two values either literals as in "Hello" and 3 or variables as in X and Counter. Most languages use the same operators for comparing both numbers and strings. Perl, for example, uses separate sets of comparison operators for numbers and strings.

C#:   ==, !=

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

Syntax Example:
//Does C# evaluate the math correctly? No!
if (.1 + .1 + .1 == .3)
MessageBox.Show("correct");
else
MessageBox.Show("not correct");
JavaScript:   ==, !=

Common comparison operators:

== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

Syntax Example:
//Does JavaScript evaluate the math correctly? No!
if (.1 + .1 + .1 == .3) {
document.write("correct");
}
else {
document.write("not correct");
}




Empty String Check

[Other Languages] 

Languages Focus

An empty string is a zero length string, a string that is equal to null (""), or not assigned. In some languages, you can check if a string is empty by comparing it to an empty string (""). Some languages distinguish between nil and null ("") so checking if the length is 0 is easier.

C#:   String.IsNullOrEmpty

The .Net framework offers a static method in the string class: String.IsNullOrEmpty.

Syntax Example:
String s;
 
s = "";
//s = null; //Uncomment to test 2nd case.
 
if (String.IsNullOrEmpty(s))
{
  MessageBox.Show("empty string");
}
[Not specified yet. Coming...]




Logical Operators

[Other Languages] 

Languages Focus

Logical operators perform conditional and, or, and not operations. Some languages support both binary logical operators that link two and unary logical operators negate (make opposite) the truth value of its argument. Finally, some languages short circuit logic. For example, with this or that, if this is an expression returning true, then that is never executed.

C#: 

Same as C++ and Java. C# logical operators:

& and, as in this and that No Short Circuit
&& and, as in this and that short circuits
| or, as in this or that No Short Circuit
|| or, as in this or that short circuits
! Not, as in Not This
^ either or, as in this or that but not both

Syntax Example:
//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) 
{
  //Do something.
}
JavaScript: 

JavaScript logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This

JavaScript always short circuits. Given the expression this || that, if this evaluates to true, then that is never executed.

Syntax Example:
//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}




String Concatenation

[Other Languages] 
C#:  "String Concatenation" +

C# performs implicit casting of numbers to strings. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

Alternatively, you can use the System.Text.StringBuilder class which frequently but not always provides faster code.

Syntax Example:
String FirstName;
String LastName;
Int16 Age;
FirstName = "Mike";
LastName = "Prestwood";
Age = 43;
Console.WriteLine(FirstName + " " + LastName + " is " + Age + ".");
  
//Implicit casting of numbers.
//
//This fails:
//MessageBox.Show(3.3);
//
//This works:
MessageBox.Show("" + 3.3); 
JavaScript:  "String Concatenation" +

To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. JavaScript performs implicit casting when concatenating a string and a number. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.

Syntax Example:
 
// -->




Unary Operators

[Other Languages] 

General Info: Unary Operator

An operation with only one operand (a single input). Common unary operators include + plus, - minus, and bitwise not. Some operators can function as both unary and binary operators. For example, + and - operators can serve as either.

Languages Focus

What unary operators are supported in additoin to the standard plus, minus, and bitwise not.

C#: 

An operation with only one operand (a single input). The following are the C# unary operators: +, -, !, ~, ++, --, true, or false. 

JavaScript: 

An operation with only one operand (a single input). JavaScript unary operators include ++ and --. They can be used either before or after a variable as in: a++, b--, and ++a, and --b.

Examples:

iCounter++;
iCounter--;
 
++iCounter;
--iCounter;
Syntax Example:
var iCounter=0;
 
for (iCounter=0;iCounter<=5;iCounter++)
{
document.write("Count is " + iCounter + "<br>");
}




 
Commands
 

Common commands (procedures and functions). A function returns a value. Optionally, it may also perform an action prior to returning a value. A procedure does not return a value or it returns void or null.

Left of String

[Other Languages] 
C#:   Substring

Above returns "abcd" on a string literal. You can, of course, use VarName.Substring(0, 4).

Syntax Example:
Console.WriteLine("abcdefgh".Substring(0, 4));
JavaScript:   substr

Above returns "Mike P".

SubStr(StartIndex, NumberOfCharacters)

Notice JavaScript is 0 based (the first character is character 0).�0 is start character, 6 is number�of characters).�

You can also use substring where both numbers are indexes:

SubString(StartIndex, EndIndex)

The following returns "re".

var sName;
sName = "Mike Prestwood";
sName = sName.substring(6, 8);
document.write(sName);
Syntax Example:
var sName;
sName = "Mike Prestwood";
sName = sName.substr(0, 6);
document.write("Hello " + sName);




 
OOP Basics
 

Some languages support object-based concepts such as Paradox, Access, and VB Classic. Other languages have OO extensions and fully support object orientation in a hybrid fashion (such as C++ and Dephi for Win32). Finally, some lanages such as C#, VB.Net, Prism, and Java are entirely written in OO. Meaning, every line of code written must occur within a class).

Base Class

[Other Languages] 

Languages Focus

When you create a class, it is either a base class or inherits from another class. Some languages require all classes to inherit from a common base class and some do not.

C#:   System.Object

In C#, the Object keyword is an alias for the base System.Object class and is the single base class all classes ultimately inherit from.

Syntax Example:  
//Specify both namespace and class:
public class Cyborg : System.Object 
{ }
  
//Use shortcut alias:
public class Cyborg : Object 
{ }
  
//None, default is System.Object
public class Cyborg
{ }
JavaScript:   Not Supported




Class..Object

[Other Languages] 

Languages Focus

In short, a class is a data type, and an object is an instance of a class type. A class has methods (routines), properties (member variables), and a constructor. The current values of the properties is the current state of the object. The UML is one of the diagraming disciplines that allows you to document the various changing states of a series of objects.

C#:   class...new

In C#, you use the class keyword to specify a class and you signify its parent with a colon and the name of the parent class. When you instantiate an object from a class, you use the new keyword.

Syntax Example:

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
//No need to clean up with managed classes.
//The garbage collector will take care of it.
JavaScript:   Limited, class..new

Creating classes in JavaScript is not really OOP, but rather a super type. That is, a type that has some class-like features but is missing the necessary OOP requirements.

There is nothing in Javascript to stop you from accessing the functions within your class outside of the class so this is not fully OOP but is usable.

Syntax Example:
//Class definition.
function Person() {
this.name = 'unknown';
this.age = 0;
}
 
//Use object created from class.
var Lisa = new Person();
Lisa.name='Lisa';
Lisa.age=28;




Inheritance

[Other Languages] 

The concept of a class makes it possible to define subclasses that share some or all of the main class characteristics. This is called inheritance. Inheritance also allows you to reuse code more efficiently. In a class tree, inheritance is used to design classes vertically. (You can use Interfaces to design classes horizontally within a class tree.) With inheritance, you are defining an "is-a" relationship (i.e. a chow is-a dog). Analysts using UML call this generalization where you generalize specific classes into general parent classes.

C#:   : ParentClass

In C#, you use the class keyword followed by the parent class after a colon. If you leave out the parent class, your class inherits from System.Object.

Syntax Example:

In the following example, a terminator T-600 is-an android. 

public class Android
{
}
 
public class T-600 : Android
{
}
JavaScript:   No, but sort of.

JavaScript does not offer a formal inheritance machanism. There are some tricks some developers are fond of.





Member Field

[Other Languages] 

Also known as a Class Field.

A class variable defined with a specific class visibility, usually private visibility. A member property is different than a member field. A member property uses a member field to store values through accessor methods (getters and setters). For example, it is common to use a private member field to store the current value of a property. The current values of all the class member fields is the current state of the object.

Languages Focus

What modifiers apply to member fields, if any? Typical member field modifiers include scope modifiers (private, protected, etc.) and read-only. Can you initialize the value of a member field when declared ensuring a default value?

C#: 

In C# you can set the visibility of a member field to any visibility: private, protected, public, internal or protected internal.

You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.

Finally, you can use the static modifier (no instance required) and readonly modifier (similar to a constant).

Syntax Example:
public class Cyborg : System.Object
{
  private string serialNumber = "A100";
 
  public string cyborgName; 
  public int cyborgAge = 0;
  public static readonly int seriesID = 100;
}
[Not specified yet. Coming...]




Member Method

[Other Languages] 

Also known as a Class Method.

A code routine that belongs to the class or an object instance (an instance of the class). Methods that belong to the class are called class methods or static methods. Methods that belong to an object instance are called instance methods, or simply methods.

When a method returns a value, it is a function method. When no value is returned (or void), it is a procedure method.

Methods frequently use method parameters to transfer data. When one object instance calls another object instance using a method with parameters, you call that messaging.

C#: 

In C#, you indicate a method with parens, no parens indicates a member property. Use the void return type for methods that do not return a value.

Syntax Example:

Define class:

public class Cyborg : System.Object
{
public virtual void IntroduceYourself()
{
MessageBox.Show("Hi, I do not have a name yet.");
}
}

Create object from class:

Cyborg T1 = new Cyborg();
T1.IntroduceYourself();
JavaScript: 

Not fully OOP as you can call the method outside of the class.

Syntax Example:
function Dog() {
  //Class variables here.

this.prototype.bark = function() {
//Class method code here.
}
}




Member Modifier

[Other Languages] 

Languages Focus

Traditional private, protected, public, etc. member modifiers are documented under the member visibility topic of the Cross Reference Encyclopedia. With member modifiers here, we address additional member modifiers such as method and field modifiers.

C#:  "Member Modifiers"

The method modifiers are abstract, extern, new, partial, sealed, virtual, and override. Specify C# member modifiers as follows:

abstract SomeMethod() {..}

The field modifiers are const, readonly, static, volatile. Specify field modifiers as follows:

readonly int MyAge;

More Info / Comment
[Not specified yet. Coming...]




Member Property

[Other Languages] 
C#:   no (), get, set

In C#, parens indicate a method and the lack of parens indicate a property. You use special get and set methods to both get and set the values of properties.

C# 3.0 introduced auto-implemented properties for use when no additional logic is required.

pulic int VendorID {get; set;}

For a read-only property, leave out the set method.

The value keyword is used to refer to the member field. Properties can make use of any of the access modifiers (private, protected, etc). It is common to use a lowercase member names for member fields ("name" in our example) and uppercase properties to manage member fields ("Name" in our example).

Syntax Example:
public class Cyborg : System.Object
{
  private string cyborgName;
 
  public string CyborgName
  {
  get {return cyborgName;}
  set {cyborgName = value;}
  }

}
[Not specified yet. Coming...]




Member Visibility

[Other Languages] 

General Info: Class Visibility Specifiers

In OOP languages, members of a class have a specific scope that indicates visibility. Standard visibility includes private, protected, and public. Private members are usable by the defining class only (fully encapsulated). They are invisible outside of the class except by friendly classes. Protected members are usable by the defining class and descendant classes only (plus friendly classes). Public members are usable wherever its class can be referenced.

Languages Focus

Traditional member visibility specifiers for fully OOP languages are private, protected, and public. Many modern OOP languages implement additional member visibilities.

Additional member modifiers are documented under the Member Modifiers topic.

C#:  "Access Modifiers"

In C#, you specify each class and each class member's visibility with an access modifier. The C# access modifiers are the traditional public, protected, and private plus the two additional .Net modifiers internal and protected internal.

Internal indicates members are accessible from types in the same assembly. Protected internal indicates members are accessible from types in the same assembly as well as descendant classes. OO purist might object to internal and protected internal and I suggest you choose private, protected, or public over them until you both fully understand them and have a need that is best suited by them.

Syntax Example:
public class Cyborg
{
private String FName;
}
[Not specified yet. Coming...]




 
OOP Details
 

More object oriented (OO) stuff.

Abstraction

[Other Languages] 

General Info: Abstract Class / Abstract Member

An abstract class member is a member that is specified in a class but not implemented. Classes that inherit from the class will have to implement the abstract member. Abstract members are a technique for ensuring a common interface with descendant classes. An abstract class is a class you cannot instantiate. A pure abstract class is a class with only abstract members.

Languages Focus

Abstraction is supported at various levels with each language. A language could enforce abstraction at the class level (either enforcing a no-instantiation rule or a only abstract members rule), and with class members (member methods and/or properties).

C#:   abstract, override

C# supports abstract class members and abstract classes using the abstract modifier.

An abstract class is a class with one or more abstract members and you cannot instantiate an abstract class. However, you can have additional implemented methods and properties.

An abstract member is either a method (implicitly virtual), property, indexer, or event in an abstract class. You can add abstract members ONLY to abstract classes using the abstract keyword. Then you override it in a descendant class with Override.

Syntax Example:
abstract public class Cyborg : System.Object
{
  abstract public void Speak(string pMessage);
}
public class Series600 : Cyborg
{
  public override void Speak(string pMessage)  
  {
    MessageBox.Show(pMessage);  
  }
}
[Not specified yet. Coming...]




Class Helper

[Other Languages] 

A. In Dephi, class helpers allow you to extend a class without using inheritance. With a class helper, you do not have to create and use a new class descending from a class but instead you enhance the class directly and continue using it as you always have (even just with the DCU).

B. In general terms, developers sometimes use the term to refer to any class that helps out another class.

C#:  "Class Helpers" Not Supported

However, developers sometimes use the term "class helper" to refer to code that helps out a class. Not truly the meaning we are using here, but you should be aware of the term's general usage.

[Not specified yet. Coming...]




Code Contract

[Other Languages] 

A.k.a. Class Contract and Design by Contracts.

A contract with a method that must be true upon calling (pre) or exiting (post). A pre-condition contract must be true when the method is called. A post-condition contract must be true when exiting. If either are not true, an error is raised. For example, you can use code contracts to check for the validity of input parameters, and results

An invariant is also a code contract which validates the state of the object required by the method.

C#:  "Code Contracts" Not Supported

Although not currently supported, there are plans for the next version of VS.Net and .Net using Requires and Ensures keywords. Look for code contracts in VS.Net 2010 and .Net 4.

If you code with VS.Net 2008 Pro or above and wish to implement contracts now, checkout the following download:

 

Syntax Example:
//Future syntax may look something like:
string SetAge(int pAge) { 
Contract.Requires(pAge>0);
}
  
string GetAge() { 
Contract.Ensures(Contract.Result() != null);
}
[Not specified yet. Coming...]




Constructor

[Other Languages] 

General Info: Class Constructor

Constructors are called when you instantiate an object from a class. This is where you can initialize variables and put code you wish executed each time the class is created. When you initially set the member fields and properties of an object, you are initializing the state of the object. The state of an object is the values of all it's member fields and properties at a given time.

Languages Focus

What is the syntax? Can you overload constructors? Is a special method name reserved for constructors?

C#:  "Constructors" Use class name

In C#, a constructor is called whenever a class or struct is created. A constructor is a method with the same name as the class with no return value and you can overload the constructor.

If you do not create a constructor, C# will create an implicit constructor that initializes all member fields to their default values.

Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

Syntax Example:
public class Cyborg
{
public string CyborgName;
  
  //Constructor.
  public Cyborg(string pName)
{
CyborgName = pName;
}
}
[Not specified yet. Coming...]




Destructor

[Other Languages] 

General Info: Class Destructor

A special class method called when an object instance of a class is destroyed. With some languages they are called when the object instance goes out of scope, with some languages you specifically have to call the destructor in code to destroy the object, and others use a garbage collector to dispose of object instances at specific times.

Desctructors are commonly used to free the object instance but with languages that have a garbage collector object instances are disposed of when appropriate. Either way, destructors or their equivalent are commonly used to free up resources allocated in the class constructor.

Languages Focus

Are object instances freed with a garbage collector? Or, do you have to destroy object instances.

C#:  "Finalizer" ~ClassName

In C# you cannot explicitly destroy a managed object. Instead, the .Net Framework's garbage collector (GC) takes care of destroying all objects. The GC destroys the objects only when necessary. Some situations of necessity are when memory is exhausted or you explicitly call the System.GC.Collect() method. In general, you never need to call System.GC.Collect().

In .Net, a finalizer is used to free non-managed objects such as a file or network resource. In C#, a finalizer is a method with the same name as the class but preceded with a tilde (as in ~ClassName). The finalizer method implicity creates an Object.Finalize method (you cannot directly call nor override the Object.Finalize method). Because you don't know when the garbage collector will call your finalizer, Microsoft recommends you implement the IDisposable interface for non-managed resources and call it's Dispose() method at the appropriate time.

Syntax Example:
class Cyborg {
public:
//Destructor for class Cyborg.
~Cyborg();
  {
  //Free non-managed resources here.
  }
};
[Not specified yet. Coming...]




Inheritance-Multiple

[Other Languages] 
C#:   Not Supported

C# does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In C#, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

More Info / Comment
JavaScript:   Not Supported

There is a trick to fake one descendant class multiple inheritance. Not really worth exploring though but...inside a constructor, call another constructor function. The new object instance will inherit any properties and methods defined in that constructor. However, the new object will not inherit methods defined in the second constructor's prototype chain.

More Info / Comment




Interface

[Other Languages] 

An element of coding where you define a common set of properties and methods for use with the design of two or more classes.

Both interfaces and abstract classes are types of abstraction. With interfaces, like abstract classes, you cannot provide any implementation. However, unlike abstract classes, interfaces are not based on inheritance. You can apply an Interface to any class in your class tree. In a real sense, interfaces are a technique for designing horizontally in a class hierarchy (as opposed to inheritance where you design vertically). Using interfaces in your class design allows your system to evolve without breaking existing code.

C#:  "Interfaces" interface

Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, but a class or struct can inherit more than one interface and it inherits only the method names and signatures, because the interface itself contains no implementations.

class MyClass: IMyInterface
{  
  public object Clone()
{
return null;
}

// IMyInterface implemented here...
}
Syntax Example:
interface IMyInterface
{
  bool IsValid();
}
[Not specified yet. Coming...]




Overriding

[Other Languages] 

General Info: Method Overriding

Where you define or implement a virtual method in a parent class and then replace it in a descendant class.

When you decide to declare a method as virtual, you are giving permission to derived classes to extend and override the method with their own implementation. You can have the extended method call the parent method's code too.

In most OO languages you can also choose to hide a parent method. When you introduce a new implementation of the same named method with the same signature without overriding, you are hiding the parent method.

C#:   virtual, override

In C#, you specify a virtual method with the virtual keyword in a parent class and extend (or replace) it in a descendant class using the override keyword.

Use the base keyword in the descendant method to execute the code in the parent method, i.e. base.SomeMethod().

Syntax Example:
class Robot
{
  public virtual void Speak()
  {
  }
}

class Cyborg:Robot
{
  public override void Speak()
  {
  }
}
[Not specified yet. Coming...]




Partial Class

[Other Languages] 

A partial class, or partial type, is a class that can be split into two or more source code files and/or two or more locations within the same source file. Each partial class is known as a class part or just a part. Logically, partial classes do not make any difference to the compiler. The compiler puts the class together at compile time and treats the final class or type as a single entity exactly the same as if all the source code was in a single location.

Languages Focus

For languages that have implemented partial classes, you need to know usage details and restrictions. Can you split a class into two or more files? Can you split a class within a source code file into two or more locations? What are the details of inheritance? Does it apply to interfaces as well?

C#:  "Partial Classes" partial

C# uses the keyword partial to specify a partial class. All parts must be in the same namespace.

Syntax Example:
class partial Cyborg: System.Object
{
}
[Not specified yet. Coming...]




Polymorphism

[Other Languages] 

A coding technique where the same named function, operator, or object behaves differently depending on outside input or influences. Usually implemented as parameter overloading where the same named function is overloaded with other versions that are called either with a different type or number of parameters. Polymorphism is a general coding technique and other specific implementations are common such as inheritance, operator overloading, and interfaces.

Languages Focus

Many languages support built-in polymorphism such as a "+" operator that can add both integers and decimals. The following documents the ability to implement developer defined polymorphism.

C#: 

C# supports the following types of polymorphism:

More Info / Comment
[Not specified yet. Coming...]




Prevent Derivation

[Other Languages] 

Languages Focus

How do you prevent another class from inheriting and/or prevent a class from overriding a member.

C#:   sealed

With C#, use the sealed keyword to prevent a class from being inherited from and to prevent a method from being overridden.

A method marked sealed must override an ancestor method. If you mark a class sealed, all members are implicitly not overridable so the sealed keyword on members is not legal.

Syntax Example:
public class Machine : System.Object
{
public virtual void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}

public class Robot : Machine
{
public sealed override void Speak(String pSentence)
{
MessageBox.Show(pSentence);
}
}
  
public sealed class Cyborg : Robot
{
}
[Not specified yet. Coming...]




Static Member

[Other Languages] 

General Info: Static Class / Static Member

A static member is a member you can have access to without instantiating the class into an object. For example, you can read and write static properties and call static methods without ever creating the class. Static members are also called class members (class methods, class properties, etc.) since they belong to the class and not to a specific object. A static class is a class that contains only static members. In the UML, these classes are described as utility classes.

Languages Focus

Languages that support static members usually at least support static member fields (the data). Some languages also support static methods, properties, etc. in which case the class member is held in memory at one location and shared with all objects. Finally, some languages support static classes which usually means the compiler will make sure a static class contains only static members.

C#:  "Static Members" static

C# supports both static members and static classes using the static keyword. You can add a static method, field, property, or event to an existing class. Also, you can designate a class as static and the compiler will ensure all members in that class are static. You can add a constructor to a static class to initialize values.

The CLR automatically loads static classes with the program or namespace.

Syntax Example:
//Static Class Example
public static class MyStaticClass
{
  //Static Method Example
  public static void MyStaticMethod()
{
// static method code
}
}
[Not specified yet. Coming...]




Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
www.prestwood.com


©1995-2024 Prestwood IT Solutions.   [Security & Privacy]