Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Data Types in C# with Examples: Value and Reference Data Type

Data Types in C# with Examples: Value and Reference Data Type

31 Aug 2024
Beginner
8.16K Views
21 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Data Types in C#

Datatypes in C# give the types of data that can be stored and processed within a program. C# has two types of data types, value data types and reference data types. In C#, value data types store the data itself, whereas reference data types store a reference to the data's memory location. Understanding these data types in C# is important for efficient memory management and performance optimization in C# programming.

In this C# Tutorial, we will explore more about data Types in C# with Examples such as  Value and Reference Data Types.

What are Data Types in C#?

In C#, data types are used to specify the type of data that a variable can hold. Data types help define the characteristics and constraints of the data, such as whether it's a whole number, a decimal number, a character, a string, and so on. C# provides a rich set of built-in data types to handle various kinds of data.

Importance of Data Types in C# programming

  • Type Safety: C# is a statically typed language, which means that variables and expressions have predefined data types. Understanding data types ensures that you assign appropriate values to variables and avoid type errors during compilation and runtime.
  • Memory Allocation: Data types determine the amount of memory required to store a particular value. By understanding data types, you can optimize memory allocation and avoid unnecessary memory consumption.
  • Data Integrity: Different data types have specific ranges and constraints. Understanding data types allows you to choose the appropriate type for a particular data value, ensuring data integrity and preventing data corruption or loss.
  • Arithmetic Operations: Data types define the set of valid arithmetic operations that can be performed on the data. By understanding the data types involved in an arithmetic operation, you can ensure accurate results and prevent unexpected behavior due to implicit conversions or type mismatches.
  • Function Signatures: Data types are an essential part of function signatures in C#. By understanding the data types of function parameters and return values, you can correctly call functions, pass arguments, and handle the results.

Read More - C Sharp Interview Questions

Types of Data Types in C#

Data types in C# are mainly divided into two categories:

TypesData Types
Value Data Typeshort, int, char, float, double etc.
Reference Data TypeString, Class, Object, and Interface

  1. Value Data Type in C#

The value data type in C# is not a specific data type itself. Instead, it refers to value types, which are data types that hold their values directly. The value data type stores its value directly in memory. There are 2 types of value data type in C# language:

  1. Predefined Data Types - such as Integer, Boolean, Float, etc.
  2. User-defined Data Types - such as Structure, Enumerations, etc.
  3. Numeric types:

    • int: Signed 32-bit integer.
    • float: Single-precision floating-point number.
    • double: Double-precision floating-point number.
    • decimal: Precise decimal representation with higher precision.
    • bool: Boolean value (true or false).
    AliasType NameTypeSize(bits)RangeDefault Value
    sbyteSystem.Sbytesigned integer8-128 to 1270
    shortSystem.Int16signed integer16-32768 to 327670
    intSystem.Int32signed integer32-231 to 231-10
    longSystem.Int64signed integer64-263 to 263-10L
    byteSystem.byteunsigned integer80 to 2550
    ushortSystem.UInt16unsigned integer160 to 655350
    uintSystem.UInt32unsigned integer320 to 2320
    ulongSystem.UInt64unsigned integer640 to 2630

    Character types:

    • char: Single Unicode character.
    AliasType nameSize In(Bits)RangeDefault value
    charSystem.Char16U +0000 to U +ffff‘\0’

    Structures (structs):

    User-defined value types are created using the struct keywords

    Example

    Let's elaborate on this in C# Compiler.
     using System;
    namespace ValueTypeTest
    {
     class ScholarHat
     {
    
     static void Main()
     {
     char a = 'S';
     int i = 89;
     short s = 56;
     long l = 4564;
     uint ui = 95;
     ushort us = 76;
     ulong ul = 3624573;
     double d = 8.358674532;
     float f = 3.7330645f;
     decimal dec = 389.5m;
    
     Console.WriteLine("char: " + a);
     Console.WriteLine("integer: " + i);
     Console.WriteLine("short: " + s);
     Console.WriteLine("long: " + l);
     Console.WriteLine("float: " + f);
     Console.WriteLine("double: " + d);
     Console.WriteLine("decimal: " + dec);
     Console.WriteLine("Unsinged integer: " + ui);
     Console.WriteLine("Unsinged short: " + us);
     Console.WriteLine("Unsinged long: " + ul);
     }
     }
    }
    
    

    Explanation

    This C# code demonstrates the use of various value types. It declares and initializes variables of different value types, including char, int, short, long, uint, ushort, ulong, double, float, and decimal. Then, it prints their respective values using Console.WriteLine().

    Output

    char: S
    integer: 89
    short: 56
    long: 4564
    float: 3.733064
    double: 8.358674532
    decimal: 389.5
    Unsinged integer: 95
    Unsinged short: 76
    Unsinged long: 3624573
    

    1. Reference Data Type in C#

    Reference data types in C# are types that store references to objects rather than the actual values. They hold a memory address that points to the location of the object in memory. Reference types are allocated on the heap and are accessed through a reference (or a pointer) to that memory location. The built-in reference types are string and object.

    • String: It displays an array of Unicode characters and the type name is “System.String”. So, both strings are equivalent.

    Example:

     string s1 = "hello"; // creating through string keyword 
    string s2 = "welcome"; // creating through String class
    
    
      Object: In C#, Object is the direct or indirect ancestor of all kinds—predefined and user-defined, reference types and value types. In essence, it serves as the root class for all C# data types. It requires type conversion before values may be assigned. Boxing describes the process of converting a value type variable into an object.

    Example:

      using System;
     namespace ValueTypeTest
     {
     class Program
     {
     static void Main()
     {
     string a = "Scholar";
     a += "for";
     a = a + "Scholar";
     Console.WriteLine(a);
     
     object obj;
     obj = 20;
     Console.WriteLine(obj);
     Console.WriteLine(obj.GetType());
     }
     }
     }
    

    Output:

    ScholarforScholar
    20
    System.Int32
    Conclusion
    In this article, We have discussed the importance of understanding data types, the common datatypes in C#, and best practices for using datatypes. Now that you have a deeper understanding of datatypes in C#, it's time to put your knowledge into practice and start building amazing applications. Happy coding! Also, Consider our C# Programming Course for a better understanding of all C# concepts.

FAQs

Q1. What are the main data types in C#?

  • Char
  • Integer
  • Float
  • Boolean

Q2. How many types are there in C#?

C# supports nine integral types: sbyte , byte , short , ushort , int , uint , long , ulong , and char .

Q3. Why do we use datatype in C#?

C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language

Q4. What is list data type in C#?

In C#, a list is a data structure that represents a collection of items that can be of any data type. Lists are implemented as classes in C#, and they provide methods for adding, removing, and modifying elements, as well as for accessing elements by their index.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Full-Stack .NET Developer Certification TrainingOct 13SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this