Introduction To Types In C#

In this article, you will learn about Types in C#.

What is Type?

  • Indicates the type of data stored in variables.
  • All data and code is defined within a Type.
  • C# program is a collection of the following Types.

    • Built-in or pre-defined types
      Eg - int, byte, char, string, object, …
    • User defined types
      Eg - Classes, structs, enums, interfaces, delegates
  • Types can be instantiated and used by calling methods, get and set properties, etc.

C# program is made of programming instructions. Instructions consist of variables. Variables are declared using Types. The variable types in C# include: int, byte, char, string, enum, struct, class, interface, delegate. C# program uses Common Type System (CTS) defined by .NET framework. Due to the object-oriented nature of C#, global variables and global methods are not supported in a program.

Types can be converted from one type to another with restrictions in some cases. Types are organized into namespaces, files, and assemblies.

Types contain data members like fields, constants, arrays, events. They can also contain function members like methods, operators, constructors, destructors, properties, indexers, and other types like classes, structure, enumeration, interfaces, and delegates.

Types

The CTS defines Types into two categories.

  1. Value type

    Value type contains actual data on stack directly. They cannot contain null values.
  2. Value types in CTS are,

    • Primitives Eg int count; float sum;
    • Enumerations Eg enum status {yes, no};
    • Structure Eg struct point {intx, y;}

  3. Reference type
  4. Reference type contains references to objects. The reference is stored on stack while the actual object is on managed heap. A Reference type can be null.

    Reference types in CTS are,

    • Root Eg- Object
    • String Eg- string name;
    • Classes Eg - class Line: Shape { . . .}
    • Interfaces Eg - interface IDrawable {. . .}
    • Arrays Eg - string[] a = new string[10];
    • Delegates Eg - delegate void operation();

In .NET applications, reference type variables are allocated on managed heap. Managed heap is controlled by garbage collector which is the component of CLR. It does automatic memory management during the execution of .NET application.

Value type variables are allocated on stack memory. They are not managed by garbage collector. So there is no pressure on garbage collector.

The differences between value type and reference type are mentioned in the following table.


Value type   
Reference type
Variable holdsActual valueMemory location
Allocated onStack, memberHeap
NullabilityAlways has valueMaybe null
Default Value0null
Assignment meansCopying actual dataCopying reference

Type Conversion

Conversion of value of an expression of one data type into another data type is known as Type conversion.

There are two types of type conversion.

  1. Implicit Conversion

    Implicit conversion means converting the lower precision data into higher precision without any loss of data. This conversion occurs automatically.

    Example -
    1. Int x = 4568  
    2. Long y = x; //implicit conversion  
  1. Explicit Conversion

    Explicit conversion requires an explicit cast. This is done by putting the type in parentheses (). This conversion is not always successful. If successful, it may or may not be converted, with possible loss of data.

    Example -
    1. Int x = 456891  
    2. Short y = (short)x; //explicit  
    3. Double d = 2.234567898765;  
    4. Float f = (float)d; //explicit  

Local Variable Type inference

C# offers a keyword called “Var” that allows a developer to declare a variable without explicitly declaring the type of it. The declared variable gets its data type as soon as it is initialized. The data type of that variable is known by data type of initialized value.

Example -

  1. Var inum = 10; //same as int inum = 10  
  2. Var fnum = 10.5 f; // same as float fnum = 10.5f  
  3. Var dobj = new date(); // same as Date dobj = new Date();  
  4. Var Imyf list = new List < int > (); // sameas List<int> lmyflist = new List<int>();  

Note

If a “var” type is declared, it is implicitly type safe because the data type is inferred from the expression used to initialize it. A compile time error occurs if the type is changed after it has been declared.

There are some rules which should be followed while working with local variable type inference.

  1. Local variable type inference variables must be initialized with some value or expression at the time of declaration.
  2. Local variable type inference types can be created only inside a method or a block.
  3. Once the type of value or expression is assigned to such type of a variable, the type of value the variable holds cannot be changed.
  4. Local variable type inference cannot be used as a return type of methods and cannot be used in argument list of methods.
  5. The compiler-time type of the initialize expression cannot be null.

    Example - 
     

    var obj=null; //error