C# Tutorials – Lesson 1 : Basic Data Types and Variables (int, double, float, etc…)

Google+ Pinterest LinkedIn Tumblr +

Primitive Data Types

Primitive data types in C# are technically contained in wrapper classes(if you do not know what this means, do not worry about it). However, at compile time, they are not really treated as classes, which improves efficiency.

There are 15 different primitive types in C#. The .NET wrapper class name is in parethesis(my apologies for the poor formatting, tables are not supported for some reason).

Integer types:

  • bool(Boolean)-Logic Value | Values: True or False | Memory: 8 bits
  • byte(Byte)-Unsigned Byte | Values: 0 to 255 | Memory: 8 bits
  • sbyte(SByte)-Signed Byte | Values: -128 to 127 | Memory: 8 bits
  • short(Int16)-Signed Integer | Values: -32,768 to 32,767 | Memory: 16 bits
  • ushort(UInt16)-Unsigned Integer | Values: 0 to 65535 | Memory: 16 bits
  • int(Int32)-Signed Integer | Values: -2,147,483,648 to 2,147,483,647| Memory: 32 bits
  • uint(UInt32)-Unsigned Integer | Values: -2,147,483,648 to 2,147,483,647| Memory: 32 bits
  • long(Int64)-Signed Integer | Values: -922337203685477508 to 922337203685477507 | Memory: 64 bits
  • ulong(UInt64)-Unsigned Integer | Values: 0 to 18446744073709551615 | Memory: 64 bits
  • char(Char)-Unicode Character | Values: Any character | Memory: 16 bits

Decimal types:

  • float(Single)-Single Precision Float | Values: -3.402823e38 to 3.402823e38 | Memory: 32 bits | Precise up to 7 digits.
  • double(Double)-Double Precision Float | Values: -1.79769313486232e308 to 1.79769313486232e308 | Precise up to 15 digits.
  • decimal(Decimal)-Very Precise Type | Values: ±1.0 × 10e−28 to ±7.9 × 10e28 | Memory: 128 bits| Precise up to 29 digits

Other:

  • string(String)-sequence of chars

Now that you know the types and sizes of data that can be represented, let’s see how to create variables of a given type. You should always give the variable a value when you declare it. This will avoid problems such as trying to use a variable before you give it a value (a runtime error occurs).

Integer/Decimal Types:

  • int myInt = 2;
  • ushort myUShort = 5;
  • double myDouble = -334.454;

String:

  • string myString = “Hello World!”;
  • string myString = “”; //Empty String

Here is an example of how to use variables in a console appliction:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string myString = “Hello World!”;
Console.WriteLine(myString);

int myInt = 5;
double myDouble = 43435.343;
Console.WriteLine(“myInt=” + myInt);
Console.WriteLine(“myDouble=” + myDouble);

Console.WriteLine(“\nPress Enter to Continue…” + a);
Console.Read();
}
}
}

Share.

About Author

Leave A Reply