X-mas Sale: Get Upto 40% 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.95K Views
21 min read
Learn with an interactive course and practical hands-on labs

Best Free C# Course: Learn C# In 21 Days

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

  • Char
  • Integer
  • Float
  • Boolean

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

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

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this