You are here

C# Language Basics

C# Language Basics

 

 

C# Language Basics

This article provides an overview of the C# Language. The various elements and building blocks of the C# language are explained.

Background

 

What is C# all about?

C# was developed at Microsoft. It is an object-oriented programming language and provides excellent features such as strong type checking, array bounds checking and automatic garbage collection. We will explore these and several other features in this article.

C# has features that make it an excellent choice for developing robust distributed n-tier Enterprise applications, web applications, windows applications and embedded systems. It is used for building applications ranging from the very large that use sophisticated operating systems, down to the very small having specialist functions

Getting Started:

Here is a very simple “Hello World” program written using C#. The code for C# program is written in text files with an extension “.cs”
Example:
1) Create a text file “First.cs”
2) Type the following code and ‘save’

 

 

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

 

3) From the command line compile the above code by typing the following
csc First.cs
4) This creates First.exe
5) Run this exe from the command line and you see an output –
Hello World

Having seen the example above we will now review the concepts and elements of the C# programming language. After that we will review the above example once again to understand what each line of code does. To get a better grasp of the C# language it is helpful if you have some programming experience and even better if you have experience in Object Oriented Programming. We now examine the C# language concepts and elements one by one.

A) OOP

C# is an object oriented Programming language and it supports the Object Oriented Programming Methodology. When creating a software solution you can represent the real world entities as “objects” of different “types”.

a. Types:C# supports mainly two kinds of types: value types and Reference types. The difference lies in the way in which handles these tow kinds of types. Examples of value types are – char, int, structures, enums . Examples of Reference types are – class, interface, delegate, arrays

i. Variables represent storage locations. Every variable is of a specific ‘type’. This determines what values can be stored in it.

ii. Field is a variable that is associated with a Class or Struct, or an instance of a class or struct.

iii. Parameters: There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.

iv. Classes: Classes are blueprints for objects. You instantiate an object from class. An object thus instantiated if said to be of a reference types. As C# is an Object Oriented Programming Language a class can inherit from another class, and can implement interfaces. Each Class can have one or members such as methods, properties, constants, fields, events, constructors, destructors and so on.

v. Structs: Structs are similar to classes in many ways. They have members and they can implement interfaces. They are fundamentally different from classes. STRUCTS are value types. STRUCT values are stored "on the stack" or "in-line". They cannot be inherited from any other class or reference type.

vi. Interfaces: What is an interface? An Interface simplifies a complex process by providing easy to use methods.  Consider you need to change the channel on your TV or increase its volume, how do we do this, we use a Remote Control to change the channel or increase the volume.  In this context, a Remote Control acts as an interface between you and your TV.  Using a Remote Control one can perform required operation and control various functionality available in TV.

An interface defines a contract. When a class or a struct implements an interface with the help of methods and properties. A type (CLASS or STRUCT) that implements an interface must adhere to its contract. Interfaces can contain methods, properties, events, and indexers as members.

vii. Delegates: C# implements the functionality of function pointers using Delegates.
A delegate instance encapsulates a list of one or more methods, each of which is referred to as a callable entity. When a delegate instance is invoked it causes the delegate instance's callable entity to be invoked.

viii. Enums: An enum type declaration defines a type name for a related group of symbolic constants.

ix. Predefined types: The predefined value types include

  • signed integral types (sbyte, short, int, and long)
  • unsigned integral types (byte, ushort, uint, and ulong)
  • floating-point types (float and double)
  • bool
  • char
  • decimal

x. Nullable types These are constructed using the ‘?’ type modifier.
int? is the nullable form of the predefined type int.
int? x = 42;
int? z = null;

The nullable type is a structure. This structure has two members :

- A value of the underlying type (“Value”)
- A Boolean null indicator (“HasValue”)

HasValue is true for a non-null instance and false for a null instance. When HasValue is true, the Value property returns the contained value.
When HasValue is false, an attempt to access the Value property throws an exception.
if (x.HasValue) Console.WriteLine(x.Value);

An implicit conversion exists from any non-nullable value type to a nullable form of that type.

B) Namespaces

C# programs are organized using namespaces. Namespaces provide a hierarchical means of organizing the elements of one or more programs. They also provide a way of presenting program elements that are exposed to other programs. For instance in our example

 

 

class myClass
static void Main()
Console.WriteLine("Hello World");
}

 

The statement – “using system;” helps us use the “Console” class in it. A namespace-declaration consists of the keyword namespace, followed by a namespace name and body

 

 


namespace Company1.Dept2
{
class manager {}
class emp {}
}

namespace Company1
{
namespace Dept2
{
class manager {}
class emp {}
}
}

 

Namespaces are open-ended, and two namespace declarations with the same fully qualified name contribute to the same declaration space In the example

 

 


namespace Company1.Dept2
{
class manager {}
}

namespace Company1.Dept2
{
class emp {}
}

 

the two namespace declarations above contribute to the same declaration space,

Assemblies Assemblies are used for physical packaging and deployment. An assembly can contain the executable code and references to other assemblies.

C) Language Grammar

a. Expressions: An expression is a sequence of operands (variables, literals, etc) and operators An expression can be classified as one of the following:

  • value
  • variable
  • namespace
  • type
  • method group
  • property access
  • event access
  • indexer access
  • void or Nothing

The output of an expression can never be a namespace, type, method group, or

b. Statements:C# statements can be classified as one of the following:

  • labeled-statement
  • declaration-statement
  • embedded-statement
  • embedded-statement: (statements that appear within other statements)
  • empty-statement
  • expression-statement
  • selection-statement
  • iteration-statement
  • jump-statement
  • try-statement
  • checked-statement
  • unchecked-statement
  • lock-statement
  • using-statement

c. Constants: A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants can depend on other constants within the same program.

class myClass
{
public const int A = 1;
public const int B = A + 1;
}

d. Fields: A field is a member that represents a variable associated with an object or class.

e. Operators: The operators of an expression indicate which operations to apply to the operands. Examples of operators: +, -, *, /, new. There are three kinds of operators:

  • Unary operators.The unary operators take one operand and use either prefix notation (such as –-counter) or postfix notation (such as counter++).
  • Binary operators. The binary operators take two operands and all use infix notation (such as intA + intY).
  • Ternary operator. Only one ternary operator, ?:, exists; it takes three operands and uses infix notation (condition? intX: intY).

Certain operators can be overloaded. Operator overloading permits user-defined behavior for the operator.

f) Methods: A method is a member of the class. It implements functionality or behavior or action that can be performed by an instance of that class. Methods can have one or more formal parameters, an optional return value

g) Properties: A property is a member of the class. It provides access to a feature or characteristic of an instance of the class. In the example below: class car has a property CarColor

 

 


public class car
{
private string _CarColor;
public string CarColor
{
get
{
return _CarColor;
}

set
{
_CarColor = value;

}
}

}

 

h) Event: An event is also a member of the class. It enables an object or class to provide notifications when an event occurs. Example

 

 


public delegate void EventHandler(object sender, System.EventArgs e);
public class Button
{
public event EventHandler Click;
public void Reset() {
Click = null;
}
}

using System;
public class Form1
{
public Form1() {

Button1.Click += new EventHandler(doSomething);
}
Button Button1 = new Button();
void doSomething(object sender, EventArgs e) {
Console.WriteLine("Button1 was clicked and I did Something!");
}
public void Disconnect() {
Button1.Click -= new EventHandler(doSomething);
}
}

 

i) Comments: Two forms of comments are supported: delimited comments and single-line comments. A delimited comment begins with the characters /* and ends with the characters */. Delimited comments can occupy a portion of a line, a single line, or multiple lines. A single-line comment begins with the characters // and extends to the end of the line.

 

 


/* This is my First Program
This is where it gets started
*/
class myFirstProgram
{
static void Main() {
System.Console.WriteLine("Welcome Aboard!"); // Comment
}
}

 

j) Conditional Statements The if statement selects a statement for execution based on the value of a Boolean expression. Examples:

if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement
if (x) if (y) F(); else G();

if (x)
{
if (y) {
F();
}
else {
G();
}
}

The switch statement : Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it
Example:

switch (iMatch) {
case 0:
Matched_Zero();
break;
case 1:
Matched_One();
break;
default:
Matched_None();
break;
}

k) Iteration statements : Iteration statements repeatedly execute an embedded statement.
Types of iteration statements:

while-statement
do-statement
for-statement
foreach-statement

Keywords in C#
 

l) Conversions A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit. A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.

A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.

m) Arrays An array is a data structure. It contains one or more variables that are accessed through computed indices. The elements of the array, are all of the same type.

n) Memory Management: One of the most important features of C# is automatic memory management implemented using a ‘garbage collector’. The process scans thru the objects created in the program and if the object can no longer be accessed the memory is cleared up

o) Indexers : An indexer enables an object to be indexed in the same way as an array.
Indexer declarations are similar to property declarations. The indexing parameters are provided between square brackets. Example

 

 

 


{
{
}
{
{
}
{
}
}

  class Test
static void Main()
AllmyCars c = new AllmyCars();
c[1] = “Alpha Romeo”;
}

<

 

 

Forums: