C# Data Types

C# Code Snippets Data Types
Share:

About

In this code snippet, we will take a look at data types in C#.

Data types are used to define the type of data a variable can hold(other members have data types too but it’s not important for now). For example, to store whole numbers you can use int, string for text, char for a single character, double for numeric values with decimal points … Data types also differ in size, byte can hold values from 0 to 255, short can hold values from -32,768 to 32,767, int can hold values from -2,147,483,648 to 2,147,483,647, … 

Also, there are two kinds of data types, reference and value types. Reference types(object, classinterfacedelegaterecord) only contain a reference(or referred to as pointers in other languages) to the actual value/object meanwhile value types(int, char, float, …) contain the actual value in the memory location referenced by the variable name. Read more about it in this post here.

This was just a quick overview of data types. You can find out more here

Let’s look at the code example below to see how to use data types.

Code:

using System;

namespace DataTypes
{
    class Program
    {
        static void Main(string[] args)
        {
            //integer holds whole numbers
            int myIntegerVariable = 1;
       
            //double holds a decimal number 
            double myDoubleVariable = 1.25;

            //float holds a decimal number 
            float myFloatVariable = 1.25f;

            //strings hold text
            string myTextVariable = "Hello World.";

            //char holds a single character
            char myCharVariable = 'a';

            //bools hold true/false
            bool myBooleanVariable = false;

            //Those were some of the more commonly used data types.
            //You can find a list of all the other data types here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table

            Console.WriteLine(myIntegerVariable);
            Console.WriteLine(myDoubleVariable);
            Console.WriteLine(myFloatVariable);
            Console.WriteLine(myTextVariable);
            Console.WriteLine(myCharVariable);
            Console.WriteLine(myBooleanVariable);

            Console.ReadLine();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger