Exforsys.com
 

Sponsored Links

 

C Sharp Tutorials

 
Home Tutorials C Sharp
 

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



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





p) Partial type declarations Partial type declarations allow type (class, struct, or interface) dec




 

 

Comments


sivaganesh247 said:

  hi<br />
can any body send the full material of C#.NET 2005 to me.
June 24, 2006, 3:10 am

sivaganesh247 said:

  Those who send vb.net,asp.net material ,its very useful.like that pls send c#material also.pls send
June 24, 2006, 3:12 am

Manoj Kumar said:

  hi
can any body send the full material of C# latest version to me

Thanks
Manoj kumar
July 8, 2006, 11:50 am

tanya said:

  looking for c material
July 15, 2006, 5:42 pm

tanya said:

  looking for c material
July 15, 2006, 5:44 pm

tanya said:

  looking for latest c material
July 15, 2006, 5:53 pm

srivani111 said:

  Can u send me latest notes of C# with examples
December 1, 2006, 8:41 pm

krishnam said:

  I am new to this technology. Please mail me the complete material ASAP.
December 16, 2006, 2:06 am

BObidare said:

  Kindly mail me the complete materials and make the pages printer friendly.
December 18, 2006, 9:15 am

Thusare said:

  Those who send vb.net,asp.net material ,its very useful.like that pls send c#material also.pls send
January 11, 2007, 10:49 am

Thusare said:

  Hi I am student I like to learn VB.NET & C#.NET but I haven't any idea that about, thear for Please give me oppinian and how to start learn,send me thearcing matrial my e-mail

Thankig
Thusare
January 11, 2007, 10:59 am

shubham saraswat said:

  excellent stuff
January 14, 2007, 8:52 am

Jose Luis Mendoza Mesia said:

  Hi I am student I like to learn VB.NET & C#.NET but I haven't any idea that about, thear for Please give me oppinion and how to start learn,send me thearcing material my e-mail.
P.S: Please could you give me some example for working with Windows Application and Web example.

Jose Luis

April 17, 2007, 5:56 pm

SEMS said:

  if someone send any information to Jose Luis ,can you send this information or documantation to me ?
My name is SEMS
mail : turksems@gmail.com
from now ,thanks :)
April 22, 2007, 5:24 pm

Sally Nabil Radwan said:

  Hi I am student I like to learn langue of php , xml and html but I haven't any idea that about, thear for Please give me oppinian and how to start learn,send me thearcing matrial my e-mail
salynabel@hotmail.com



April 29, 2007, 12:26 pm

maansee said:

  Can anybody send me the interoperability between c# and .Net,Com and ActiveX Interoperability
My email Id is monika_rathi786@yahoo.com
June 10, 2007, 12:29 am

S.S.SIVAPRASAD said:

  Pls tel to me, how to use the C# web application controls(C# asp.net) using system side C# code.


E-mail: sivacdotnet@gmail.com
October 8, 2007, 4:50 am

Eric said:

  I am looking for help in setting up a console application. I kinda got the jist, but need a little help.
October 10, 2007, 5:23 pm

hashan said:

  hi ... this the best site for learning programming
November 12, 2007, 1:40 am

hashan said:

  i want examples for database binding in c#
November 12, 2007, 1:44 am

Henry Stinson said:

  It would help the readability of the sample code a great deal if the code were indented using normal rules. I think 4-space indents are good, but even 3-space indents would help a great deal. Two-space indents are often not quite enough for good code readability.
January 8, 2008, 5:44 pm

jassu said:

  very useful material for C# basics
February 18, 2008, 7:58 am

user said:

  Hi .I like to learn VB.NET & C#.NET but I haven't any idea that about, thear for Please give me your oppinian.where can l start ?and how to start learn,send me thearcing matrial my e-mail .please guide me.

Thanking
ammu
my e-mail-id:mmphs.user@gmail.com
May 7, 2008, 7:11 pm

dharmendra t said:

  i dont have much more knowledge in c and c is it possible to learn c#
June 14, 2008, 12:28 am

madhavi said:

  Pls tel to me, how to use the C# web application controls(C# asp.net) using system side C# code.
October 24, 2008, 2:35 am

anirudh girey said:

  hi i like this article
November 26, 2008, 1:56 am

Aamir said:

  Hi I am student I like to learn VB.NET & C#.NET but I haven't any idea that about, thear for Please give me oppinion and how to start learn,send me thearcing material my e-mail.
P.S: Please could you give me some example for working with Windows Application and Web example.

Aamir
January 24, 2009, 2:45 am

jagadish said:

  Hi,
I am student,i Have To learn .NET(vb,c#,Ado&Asp.net) i can i start the learn of this .NET i have no idea about this .NET so, send me best material with examples.


Jagadish
February 12, 2009, 11:44 pm

Niranjan said:

  give me some sample programs for grid view control in C#.net
February 9, 2010, 7:44 am

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 

Copyright © 2000 - 2010 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape