What We Do

  • Our Focus is You
    We focus on your online needs so that you can focus on your customer's needs. There are numerous way in which we can help you. We begin by reviewing your business goals, your marketing objectives, and your competitive position, and then we develop your online presence to meet your needs.
  • Dynamic Content
    Today's web applications require dynamically driven content, and much of that content is provided by a database and a programming language operating in harmony to produce the desired results. MySQL and PHP are two of the most popular web development tools utilized to produce dynamic web sites. We can help you take control and begin building truly dynamic web content which is easier to maintain, is more responsive to your users, and can alter its appearance based upon differing situations. Contact Us today to discuss your custom development needs.
  • Content Management Systems (CMS)
    We can deploy CMS applications to allow organizations to edit content easily, which significantly cuts down on costly professional maintenance fees. Our CMS expertise covers Joomla, Wordpress and Blogger platforms. We are ready to help you choose which works best for your specific needs. Contact Us today to begin taking control of your content.
Powered by Blogger.

C# Data Types

In C#, variables are categorized into the following types:

  • Value types
  • Reference types
  • Pointer types

Value Types

Value type variables can be assigned a value directly. They are derived from the class System.ValueType.

The value types directly contain data. Some examples are int, char, float, which stores numbers, alphabets, floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.

The following table lists the available value types in C# 2010:
TypeRepresentsRangeDefault
Value
boolBoolean valueTrue or FalseFalse
byte8-bit unsigned integer0 to 2550
char16-bit Unicode characterU +0000 to U +ffff'\0'
decimal128-bit precise decimal values with 28-29 significant digits(-7.9 x 1028 to 7.9 x 1028) / 100 to 280.0M
double64-bit double-precision floating point type(+/-)5.0 x 10-324 to (+/-)1.7 x 103080.0D
float32-bit single-precision floating point type-3.4 x 1038 to + 3.4 x 10380.0F
int32-bit signed integer type-2,147,483,648 to 2,147,483,6470
long64-bit signed integer type-923,372,036,854,775,808 to 9,223,372,036,854,775,8070L
sbyte8-bit signed integer type-128 to 1270
short16-bit signed integer type-32,768 to 32,7670
uint32-bit unsigned integer type0 to 4,294,967,2950
ulong64-bit unsigned integer type0 to 18,446,744,073,709,551,6150
ushort16-bit unsigned integer type0 to 65,5350

To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

namespace DataTypeApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Size of int: {0}", sizeof(int));
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Size of int: 4

Reference Types

The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.

In other words, they refer to a memory location. Using more than one variable, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic and string.

OBJECT TYPE

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. So object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.

object obj;
obj = 100; // this is boxing

DYNAMIC TYPE

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.

Syntax for declaring a dynamic type is:

dynamic <variable_name> = value;
For example,

dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables take place at run time.

STRING TYPE

The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted.

For example,

type* identifier;
A @quoted string literal looks like:

@"Tutorials Point";
The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.

Pointer Types

Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in C or C++.

Syntax for declaring a pointer type is:

type* identifier;
For example,

char* cptr;
int* iptr;

Type Conversion

Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:

  • Implicit type conversion - these conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.
  • Explicit type conversion - these conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion:

namespace TypeConversionApplication
{
    class ExplicitConversion
    {
        static void Main(string[] args)
        {
            double d = 9773.74;
            int i;

            // cast double to int.
            i = (int)d;
            Console.WriteLine(i);
            Console.ReadKey();
            
        }
    }
}
When the above code is compiled and executed, it produces the following result:

9973

C# Type Conversion Methods

C# provides the following built-in type conversion methods:

S.NMethods & Description
1ToBoolean
Converts a type to a Boolean value, where possible.
2ToByte
Converts a type to a byte.
3ToChar
Converts a type to a single Unicode character, where possible.
4ToDateTime
Converts a type (integer or string type) to date-time structures.
5ToDecimal
Converts a floating point or integer type to a decimal type.
6ToDouble
Converts a type to a double type.
7ToInt16
Converts a type to a 16-bit integer.
8ToInt32
Converts a type to a 32-bit integer.
9ToInt64
Converts a type to a 64-bit integer.
10ToSbyte
Converts a type to a signed byte type.
11ToSingle
Converts a type to a small floating point number.
12ToString
Converts a type to a string.
13ToType
Converts a type to a specified type.
14ToUInt16
Converts a type to an unsigned int type.
15ToUInt32
Converts a type to an unsigned long type.
16ToUInt64
Converts a type to an unsigned big integer.
The following example converts various value types to string type:

namespace TypeConversionApplication
{
    class StringConversion
    {
        static void Main(string[] args)
        {
            int i = 35;
            float f = 64.005f;
            double d = 8675.309;
            bool b = true;

            Console.WriteLine(i.ToString());
            Console.WriteLine(f.ToString());
            Console.WriteLine(d.ToString());
            Console.WriteLine(b.ToString());
            Console.ReadKey();
            
        }
    }
}
When the above code is compiled and executed, it produces the following result:

35
64.005
8675.309
True

C# Output

WriteLine

Console.WriteLine renders a line of text to the console. It is a useful Console method, and in its simplest form it outputs the string argument with a trailing newline. With no arguments it outputs a blank line.
Example:
using System;

class Program
{
    static void Main()
    {
      // Write an int with Console.WriteLine.
      int valueInt = 4;
      Console.WriteLine(valueInt);

      // Write a string with the method.
      string valueString = "Your string";
      Console.WriteLine(valueString);

      // Write a bool with the method.
      bool valueBool = false;
      Console.WriteLine(valueBool);
    }
}
When the above results in the following:
4
Your String
False

Empty Line

It is possible to use Console.WriteLine with no arguments. This will simply output a blank line to the Console window. This is an elegant way to output an empty line. You do not have to specify the newline character.

Example:
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("A");
        Console.WriteLine(); // Empty line
        Console.WriteLine("B");
    }
}
When the above results in the following:
A

B

Write

Console.Write method requires the System namespace to be included at the top to get the fully qualified name. The Write method does not append a newline to the end of the Console.

Example:
using System;

class Program
{
    static void Main()
    {
        Console.Write("One ");     // <-- This writes the word.
        Console.Write("Two ");     // <-- This is on the same line.
        Console.Write("Three");    // <-- Also on the same line.
        Console.WriteLine("Four"); // <-- This is on the next line.
    }
}
When the above results in the following:
One Two Three
Four

C# Basic Syntax (Classes, Objects, and Methods)

C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.

For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and display details.

Let us look at an implementation of a Rectangle class and discuss C# basic syntax, on the basis of our observations in it:

using System;
namespace RectangleApplication
{
    class Rectangle
    {
        // member variables
        double length;
        double width;
        public void Acceptdetails()
        {
            length = 4.5;    
            width = 3.5;
        }
        public double GetArea()
        {
            return length * width;
        }
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces the following result:

Length: 4.5
Width: 3.5
Area: 15.75

The using Keyword

The first statement in any C# program is

using System;
The using keyword is used for including the namespaces in the program. A program can include multiple using statements.

The class Keyword

The class keyword is used for declaring a class.

Comments in C#

Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below:

/* This program demonstrates
The basic syntax of C# programming 
Language */
Single-line comments are indicated by the '//' symbol. For example,

}//end class Rectangle  

Member Variables

Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width.

Member Functions

Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle is used as a class, which contains the Main() method and instantiates the Rectangle class.

Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:

A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

It should not be a C# keyword.

C# Keywords

Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers; however, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character.

In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual keywords.

The following table lists the reserved keywords and contextual keywords in C#:
Reserved Keywords
abstractasbaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinin (generic
modifier)
int
interfaceinternalislocklongnamespacenew
nullobjectoperatoroutout
(generic
modifier)
overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedshortsizeofstackallocstaticstringstruct
switchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatilewhile
Contextual Keywords
addaliasascendingdescendingdynamicfromget
globalgroupintojoinletorderbypartial
(type)
partial
(method)
removeselectset

Objects

An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection.

An Object in C# is an instance of a class that is created dynamically. Object is also a keyword that is an alias for the predefined type System.Object in the .NET framework.   The unified type system of C# allows objects to be defined. These can be user-defined, reference or value type, but they all inherit directly or indirectly from System.Object. This inheritance is implicit so that the type of the object need not be declared with System.Object as the base class.

In general, object type is useful where there is a requirement to build generic routines. Because values of any type can be assigned to variables of object type, object type is used mostly in designing classes that handle objects of any type that allow code to be reused. The non-generic collection classes in the .NET framework library, such as ArrayList, Queue, etc., use object type to define various collections.

Methods

A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.

To use a method, you need to:

  • Define the method
  • Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}
Following are the various elements of a method:

  • Access Specifier: This determines the visibility of a variable or a method from another class.
  • Return type: A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
  • Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
  • Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method body: This contains the set of instructions needed to complete the required activity.
Example:
Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two. It has public access specifier, so it can be accessed from outside the class using an instance of the class.

class NumberManipulator
{
   public int FindMax(int num1, int num2)
   {
      /* local variable declaration */
      int result;

      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result;
   }
   ...
}

Calling Methods in C#

You can call a method using the name of the method. The following example illustrates this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* local variable declaration */
         int result;

         if (num1 > num2)
            result = num1;
         else
            result = num2;

         return result;
      }
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
When the above code is compiled and executed, it produces the following result:

Max value is : 200

You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int FindMax(int num1, int num2)
        {
            /* local variable declaration */
            int result;

            if (num1 > num2)
                result = num1;
            else
                result = num2;

            return result;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator();
            //calling the FindMax method
            ret = n.FindMax(a, b);
            Console.WriteLine("Max value is : {0}", ret );
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces the following result:

Max value is : 200

Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* local variable declaration */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            //calling the factorial method
            Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces the following result:

Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Passing Parameters to a Method

When method with parameters is called, you need to pass the parameters to the method. In C#, there are three ways that parameters can be passed to a method:

MechanismDescription
Value parametersThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Reference parametersThis method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Output parametersThis method helps in returning more than one value.