C# Simplified

Want to learn C# but don't know where to begin? Look no further. This article, the first in a series of articles covering the language, will provide you with a good starting point.

Contributed by
Rating: 3 stars3 stars3 stars3 stars3 stars / 10
March 01, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Support file for this article is available here.


In this article, you will learn about:

  • Data Types, Variables and Operators

  • Value Types and Reference Types

  • Classes

Data Types, Variables and Operators

Data Types and Variables are the core of the C# programming language. They represent how to express numbers, characters, strings and other values in real code. For example, if you want to add two numbers, such as 100 and 200, you must write a code as shown below:

Listing 1.1

int X = 100;
int Y = 200;
int Z = x+y;
Console.WriteLine(Z);

The above code is not a complete listing but it shows the way you have to declare values.

In listing 1.1, the term int represents the built-in data type called Integer. The int is an alias for the Integer data type. Like Integer, there are lots of other data types which you can use for your programming tasks.

You will also notice three characters named X, Y and Z in the above code. They are known as variables. X, Y and Z are the names given to the variables. Variables are used to store data in the memory. Without variables you cannot store data and perform manipulations. They are the containers for the real data. 100 and 200 are the values given for the respective variables. The end result is stored in another variable called Z.

Each data type has a fixed range beyond which you cannot store values. If you attempt to store a big value for an Integer data type, the program will emit errors. Consider a scenario where you are storing a value of 500 using a Byte data type. The program will not show any errors during the compilation stage since the basic logic is correct. Instead, there will be runtime errors because you are storing too high a value for the byte data type. It will only hold values up to 255. These errors are called as Exceptions. You will learn more about exceptions in a later article.

You must always use the data type best suited to your programming needs. For example, if you are writing code for developing a calculator, it’s better to use data types which will accept large values. This will help you to avoid costly runtime errors.

Different Types of Data Types

The .NET Framework provides lot of data types which you can use for developing applications. Since these data types are provided by the Common Language Runtime (CLR), all .NET languages such as C#, Visual Basic .NET can take advantage of them. A complete list of all data types and its range values are given in Table 1.

Table 1  List of Data Types

Data Type Prefix.NET DataType Min Value Max Value
sbyteSystem.Sbyte-128127
byteSystem.Byte0255
shortSystem.Int16 -32,768 32,767
ushortSystem.UInt16065,535
intSystem.Int32 -2,147,483,648 2,147,483,647
uintSystem.UInt32 04,294,967,295
longSystem.Int64-9,223,372,036,854,775,8089,223372,036,854,775,808
ulongSystem.UInt64018,446,744,073,709,551,615
charSystem.Char065,535
floatSystem.Single1.5 x 10^-45 3.4 x 10^38
doubleSystem.Double5.0 x 10-3241.7 x 1010308
boolSystem.BooleanFalse (0)True (1)
decimalSystem.Decimal1.0 x 10-287.9 x 1028

Operators

With the help of operators, you can manipulate values and perform arithmetical operations. For instance, if you have to add three numbers you must use the addition (+) symbol. In the same way, if you have to multiply three numbers, you must use the * symbol. In programming parlance, these symbols are known as Operators. You will use them extensively when you develop applications such as calculator.

C# offers a wide variety of operators which can be used for various purposes. Table 2 lists all the available operators in C# in the order of their precedence.

Table 2 List of Operators

Name of the OperatorDescription
Primary Operators()  . []  x++ x--  new  typeof  sizeof  checked  unchecked
Unary+  -  !  - ++x --x
Multiplicative *  /  %
Additive+   -
Shift <<   >>
Relational<   >   <=   >=  is
Equality= = !=
Bitwise AND&
Bitwise XOR^
Bitwise OR|
Conditional AND && (Used for evaluating conditions using if-else)
Conditional OR ||   (Used for evaluating conditions using if-else)
Conditional?:  (Used for evaluating conditions instead of if-else)
Assignment= *= /= %= += -= <<= >>=  &= ^= !=

Let us now look at a simple C# program which illustrates the functioning of one of the operators listed in the table above.

Listing 1.2

001: using System;
002:
003: class Oper
004: {
005: public static void Main()
006: {
007:
008: int x = 50;
009: int y = 100;
010:
011: if ((x<y && y>x)) {
012:
013: Console.WriteLine("X is less than Y");
014: }
015:
016: else {
017:
018: Console.WriteLine("Condition not satisfied");
019: }
020:
021: }
022: }

In the above listing, the condition in line 11 will execute only when both the parameters are correct. If any one of the parameters is false the statements inside the else part will be printed as output.

In the next section, you will learn about the concept of value and reference types in C#.

Value Types and Reference Types

The data types in C# can be classified as Value Types and Reference Types. Value Types include all numerical data types such as Integer, Float, Byte and Decimal, etc. and you work directly with values. If you try to assign one value type to another, a bit wise copy is achieved. Listing 1.3 illustrates this concept in detail:

Listing 1.3

001: // Valtype.cs
002: // -----------
003: using System;
004:  struct Valdata
005:  {
006:   public int a;
007:   public int b;
008:  }
009:
010:  class Valtype 
011:  {
012:   public static void Main(string[] args)
013:   {
014:
015:    // Object of the Structure created
016:    Valdata v = new Valdata();
017:    v.a = 500;
018:    v.b = 600;
019:
020:    // A new variable named v1 created and passed the value of structure object
021:    Valdata v1 = v;
022:
023:
024:    //Prints 500
025:    Console.WriteLine(v.a);
026:
027:    //Prints 600
028:    Console.WriteLine(v.b);
029:
030:    // Prints 500
031:    Console.WriteLine(v1.a);
032:
033:    // Prints 600
034:    Console.WriteLine(v1.b);
035:
036:    Console.WriteLine("After Changing the value of one     variable");
037:
038:    v1.a = 900;
039:
040:    // Prints 900
041:    Console.WriteLine(v1.a);
042:
043:    //Prints 500
044:    Console.WriteLine(v.a);
045:   }
046:  }

From the above code, you will notice that if you change the value of one variable, the value of another variable will not change. The output of the above program looks like Figure 1.1.

C# Simplified

Figure 1.1

Reference types are just opposite of Value types. Classes and Interfaces are reference types. If you change the value of one variable the value of the other variable also reflects the same value. Listing 1.4 is a modified version of listing 1.3:

Listing 1.4

001: // Reftype.cs
002: // ----------
003: using System;
004:  class Valdata
005:  {
006:   public int a;
007:   public int b;
008:  }
009:
010:  class Reftype 
011:  {
012:   public static void Main(string[] args)
013:   {
014:
015:    // Object of the Structure created
016:    Valdata v = new Valdata();
017:    v.a = 500;
018:    v.b = 600;
019:
020:    // A new variable named v1 created and passed the value of structure object
021:    Valdata v1 = v;
022:
023:
024:    //Prints 500
025:    Console.WriteLine(v.a);
026:
027:    //Prints 600
028:    Console.WriteLine(v.b);
029:
030:    // Prints 500
031:    Console.WriteLine(v1.a);
032:
033:    // Prints 600
034:    Console.WriteLine(v1.b);
035:
036:    Console.WriteLine("After Changing the value of one     variable");
037:
038:    v1.a = 900;
039:
040:    // Prints 900
041:    Console.WriteLine(v1.a);
042:
043:    //Prints 900
044:    Console.WriteLine(v.a);
045:   }
046:  }

From the above listing, you will understand that even if you change the value of one variable, the value of other variable also changes (see lines 038 to 044). The output of the above program looks like Figure 1.2

C# Simplified

Figure 1.2

Boxing and Unboxing

Boxing is the conversion of a value type into a reference type. Consider the listing given below:

Listing 1.5

// Value type X defined
int X = 600;

// X boxed to a object type which is reference based
object Y = X;

On the other hand, Unboxing is the conversion of a reference type into a value type. In listing 1.6, Y can be unboxed to a value type as shown below:

Listing 1.6

// Y unboxed to an integer type
int Z = (int)Y

The only difference is that an explicit cast is required while converting a reference type into a value type as shown above.

Classes

Classes are the fundamental concept in an Object Oriented Programming Language such as C#. It would be more appropriate to discuss the meaning of a class with reference to an object. This is because these two words are interrelated. While a class is a combination of related objects, an object is an instance of the respective class. Actually, .NET Framework itself provides us with lot of classes with which you can perform a wide variety of tasks. But before applying these classes in a C# program, you have to define your own class. It is defined as shown below:

Listing 1.7

class Computer
{
// Declarations goes here
}

The opening and closing curly braces are important while declaring a class. It is in between these braces you declare variables, Main() method and also perform lot of other tasks.

Creating an instance of a class

After declaring a class you can create an instance of it by using the new keyword. The general syntax for creating an instance of a class is shown below:

Listing 1.8

YourClassname Yourobjectname = new Constructor();

Hence, for a class named Computer the declaration should be as in listing 1.9

Listing 1.9

Computer comp = new Computer();

To access a variable using the above object name, you should use the dot operator as shown in listing 1.10:

Listing 1.10

using System;
 class VarAccess
 {
  int x = 1000;
            int y = 2000;

  public static void Main() 
  {
   VarAccess va = new VarAccess();
   Console.WriteLine(va.x);
                  Console.WriteLine(va.y);
      }

 }

In the above listing, the variables x and y are declared outside the Main() method. Hence, they are called as Instance variables. You need to create an object only for accessing an Instance variable. As soon as you create a variable, .NET allocates memory and it is immediately destroyed after the execution of the program with the help of the built-in garbage collector.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials