DataTypes in C#

Ksuresh
Posted by in C# category on for Beginner level | Points: 250 | Views : 37146 red flag
Rating: 5 out of 5  
 1 vote(s)

In this Article we are going to learn about Data Types in C#

What is Data Type?

The type of data that a variable contains is called Data Type (type). A Data Type is a classification of things that share similar type of qualities or characteristics or behavior.

C# is strongly typed language so every variable and object must have a type.

There are two types of data type in C#

  1.   primitive types (or) predefined

Ex:  byte, short, int, float, double, long ,char, bool, DateTime, string, object etc..

 2.   non-primitive types (or) User Defined

Ex: class , struct , enum , interface,  delegate, array.

In C#, based on what a variable contains there is two types of built-in data type

Value types

A variable holds actual values then that type of data types are value types. These value types are stored in “stack” memory and these value types are fixed in size. If you assign a value of a variable to another variable it will create two copies.

Ex: byte, short, int, float, double, long ,char, bool, DateTime.

  • Primitive data types are value types except string, object.
  • Object type is superior to all types. It can store any type or any size of data. It helps in inheritance process.
  • Struct, enum are value types.
Reference types

A variable holds a reference to the value, then that type of data types are reference types. These reference types are stored in “heap” memory and these types are not fixed in size.  They are maintained in system managed heap but it also uses stack to store reference of the heap. Two primitive types (string and object) and non-primitive data types (class, interface & delegate) are examples of reference type.

Ex:   class, interface, delegate, string, object and array

Let us learn couple of data types and its uses with example 

Date and Time

Date time is one of the most commonly used data type in C#, here i am going to explain some of properties about it also.

Ex:

DateTime currenttime = DateTime.Now;//display’s current date time. 

Output:

int days = DateTime.DaysInMonth(2011, 7);// it displays “31”.  

Output:

Common Date Time Properties

Property          Description
Date        Gives the date component of the current instance
Day Gives the day of the month represented by the current instance
DayOfWeek  Gives the day of the week represented by the current instance
Hour  Gives the hour component of the date represented by the current instance
Minute  Gives the minute component of the date represented by the current instance
Month   

Gives the month component of the date represented by the current instance   

Now  Gives a DateTime object that is set to the current date and time, in the local time zone
TimeOfDay Gives the time of day for the current instance
Today Gives the current date
DaysInMonth  Gives no of Days in that month

Examples

DateTime now = DateTime.Now;

Console.WriteLine("Time:" + now.TimeOfDay);//it display only current time of that day.

Output:

Console.WriteLine("Current month: "+now.Month);//it display what is current month.

Console.WriteLine("To Day is: "+now.DayOfWeek);// it gives current day name.

Output:

Common DateTime Arithmetic Methods

Method          Description
AddDays    Adds or subtracts the specified number of days
AddHours Adds or subtracts the specified number of hours
AddMinutes  Adds or subtracts the specified number of minutes
AddMonths Adds or subtracts the specified number of months
AddYears Adds or subtracts the specified number of years

Examples

DateTime myDateTime = DateTime.Parse("7/28/2011 10:17:30");

TimeSpan TimeSpan = new TimeSpan(3, 4, 3, 12);

DateTime newDateTime = myDateTime + TimeSpan;

DateTime subtracttime = myDateTime - TimeSpan;

Console.WriteLine("myDateTime + TimeSpan = " + newDateTime);

Console.WriteLine("myDateTime - TimeSpan = " + subtracttime);

Output:

DateTime now = DateTime.Now;

DateTime addtwodays = DateTime.Now.AddDays(2);//it adds two days to current date and time.

DateTime addminutes = DateTime.Now.AddMinutes(50);

Console.WriteLine("Current DateTime:" + now);

Console.WriteLine("Addition of two days, DateTime:" + addtwodays);

Console.WriteLine("adition of minutes, DateTime:" + addminutes);

Output:

Common TimeSpan Members

Name  Description
Add Adds the specified TimeSpan to the current instance
Days Gets the days component of the time interval represented by the current TimeSpan
FromDays Returns a TimeSpan that represents a specified number of days
FromHours Returns a TimeSpan that represents a specified number of hours
FromMilliseconds Returns a TimeSpan that represents a specified number of milliseconds
FromMinutes Returns a TimeSpan that represents a specified number of minutes
FromSeconds Returns a TimeSpan that represents a specified number of seconds
Hours  Gets the hours component of the time interval represented by the current TimeSpan
Milliseconds Gets the milliseconds component of the time interval represented by the current TimeSpan
Minutes Gets the minutes component of the time interval represented by the current TimeSpan
Seconds Gets the seconds component of the time interval represented by the current TimeSpan
Subtract   Subtracts the specified TimeSpan from the current instance
TotalDays Gets the value of the current TimeSpan expressed as whole and fractional days
TotalHours Gets the value of the current TimeSpan expressed as whole and fractional hours
TotalMilliseconds Gets the value of the current TimeSpan expressed as whole and fractional milliseconds
TotalMinutes Gets the value of the current TimeSpan expressed as whole and fractional minutes
TotalSeconds Gets the value of the current TimeSpan expressed as whole and fractional seconds

Example on TimeSpan:

using System;

class timespan

{

public static void Main()

{

DateTime time = DateTime.Now;

TimeSpan TimeSpan = new TimeSpan(24, 00, 00);

DateTime time24 = time.Subtract(TimeSpan);

Console.WriteLine("myTimeSpan = " + TimeSpan);

Console.WriteLine("time before 24 hours = " + time24);

Console.ReadLine();

}

}

Output

Integer

byte ,sbyte, short, ushort, int ,unit, long, ulong

Name Range
Sbyte -128 to 127 
short -32768 to 32767
int -2147483648 to  2147483647
long -9223372036854775808 to 9223372036854775807
byte 0 to 255
ushort 0 to 65535
uint 0 to 4294967295
ulong 0 to 18446744073709551615

Long Example:

using System;

class longexample

{

public static void Main()

{

long inches;

long miles;

inches = 45789124565654567;

miles = inches / (5280 * 12); // 12 inches= 1 feet, 5280 feet’s= 1 mile;

Console.WriteLine(" In miles = " + miles);

}

}

 

Output:
In miles= 722681890240

Byte Example:

using System;

class byteexample

{

public static void Main()

{

byte t = 1;

int total = 0;

for (t = 1; t < 200; t++)

{

total = total + t;

}

Console.WriteLine(" Total = " + total);

}

}

Output:

Total= 19900

The smallest ineger types are byte and sbyte. For small unsigned value use byte , for small signed values use sbyte type to hold value. Whenever if you need integer larger than byte 0r sbyte but smaller than int or uint use short or ushort.

Floating point:


The flating point values are initialized as mentioned below,

For single precession value use “float “
float   a=1.1f;

For more than one precession value use “double”  
double d=2.12345;

Name  Range
float plus & minus 1.5 X 10-45 to ±3.4 X 1038
double  plus & minus 5.0 X 10-3245 to ±3.4 X 10308

floating points Example:

using System;

class floatexample

{

public static void Main()

{

double radius;

float area = 12.6f;

radius = Math.Sqrt(area / 3.1416);

Console.WriteLine("circle radius = " + radius);

}

}

Output :
circle radius= 2.002672042194

Boolean type:

The bool type gives values as true or false. And there is no conversion between integer and bool, we can’t convert ‘1’ to ‘true’ or “0” to “false”.

Boolean Example:

using System;

class integerexample

{

public static void Main()

{

bool a;

a = true;

if (a)

{

Console.WriteLine("a=" + a);

}

else

{

Console.WriteLine("a is false");

}

}

} 

Out put :
a= true;

String:

A string is a set of characters enclosed by double quotes, the fact that a string is immutable. If we once created sequence of characters to string then cannot be altered. This feature allows strings to be implemented more efficiently. And unused string objects are collected automatically by  Garbage collector.

using System;

class stringexample

{

public static void Main()

{

string str1 = "C# makes strings easy.";

string str2 = str1.Substring(2, 12);

Console.WriteLine("sub string is " + str2);

}

}

Output:

String Methods

The string type,  includes several methods. There are methods, for example, for formatting, concatenating, and comparing strings.

String Format() Example:

Format string means arranging the data in the human readable form and easily understandable. For example {0} indicates arg0,{1} indicates arg1 and so on . During the execution when format is encountered in the format of string the corresponding argument is substituted and displayed.  

using System;

class timespan

{

public static void Main()

{

string text;

string firstName = "fname";

string lastName = "lname";

text = string.Format("Your firstname ={0}, LastName {1}.", firstName, lastName);

System.Console.WriteLine(text);

}

}

Output:



Concatenating strings

There are two ways to concatenate(join together) two or more strings. First using the + operator and various concatenation methods defined by String. The method that performs concatenation is called Concat(). One of its simplest form is showing below

public static void string.Concat( string str0, string str1)

this method  returns a string that contains str1 concated to the end of str0.

Concat example:

using System;

class timespan

{

public static void Main()

{

string text;

string firstName = "Laxmi";

string lastName = "Narayana";

text = string.Concat(firstName, lastName);

System.Console.WriteLine("Full Name:" + text);

}

}

Output:

Compare Statement

static int   string.Compare( string strA, string strB)

If strA is less than strB then Compare() method  returns zero, if strA is greater than strB returns greater than zero, if  the strings are equal returns zero.

Compare method example:

using System;

class timespan

{

public static void Main()

{

string str1 = "Maruthi";

string str2 = "Narayana";

// String comparison in which case matters.

int result = string.Compare(str1, str2);

if (result < 0)

Console.WriteLine(str1 + " is less than " + str2);

else if (result > 0)

Console.WriteLine(str1 + " is greater than " + str2);

else

Console.WriteLine(str1 + " equals " + str2);

}

}

Output:

Escape characters

Escape character is used to store some special character in the variable or print on the screen. In C#, escape character is “\” (backslash)

  • \’ is used for Single quotation mark 
  •  \” is used for Double quotation mark 
  •  \\ is used for a single Backslash 
  •  \0 is used for Null 
  •  \b is used for Backspace 
  •  \f is used for Form feed
  •  \n is used for Newline 
  •  \r is used for Carriage return 
  •  \t is used for Tab character
In case you have missed my first article in this series, read - C# Fundamentals

Reference: I have taken reference of the C# 4.0 Complete reference book that I am going through these days.

Hope this article was useful. Do let me know your comment or feedback.

In case you want to learn ASP.NET with Tips and Tricks, I found .NET Tips and Tricks very useful.

In the next article, we are going to learn Date Time Data type  methods with examples. Thanks for reading.

Page copy protected against web site content infringement by Copyscape

About the Author

Ksuresh
Full Name: suresh reddy
Member Level: Starter
Member Status: Member
Member Since: 3/24/2011 3:29:04 AM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)