C# Data Types
In C#, data types specify the kind of data that can be stored in a variable. C# is a strongly typed language, meaning each variable must be declared with a specific data type. Data types define the size, range, and behavior of the data that a variable can hold. They can be broadly categorized into value types and reference types.
Here’s a detailed explanation of the data types in C#:
1. Value Types
Value types store the actual data directly in the variable. When you assign one value type variable to another, a copy of the data is made. Value types are usually stored on the stack, a memory structure that is faster to access.
Common value types include:
- Primitive data types (like
int
,float
,char
). - Enums.
- Structs.
Common Value Types:
Integral Types: Used for storing whole numbers (integers) with or without a sign (positive or negative
Floating-Point Types: Used for storing numbers with decimal points. They follow IEEE standards for floating-point arithmetic.
float
anddouble
are commonly used for general purposes. Usedecimal
for high-precision calculations like financial transactions.
Character Type: Stores a single Unicode character.
Boolean Type: Stores
true
orfalse
.Structs: Value types that can contain multiple fields and methods. Unlike classes, structs are value types and are stored on the stack.
Example:
struct Point { public int X; public int Y; }
Enums: A special value type that defines a set of named constants (enumeration).
Example:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
2. Reference Types
Reference types store a reference to the actual data, not the data itself. The reference points to a location in the heap memory, where the data is stored. When a reference type variable is assigned to another, both variables point to the same memory location.
Common reference types include:
- Classes.
- Interfaces.
- Arrays.
- Delegates.
- Strings.
Common Reference Types:
Class Types: Classes are reference types that define objects with fields, properties, methods, and other members.
Example:
class Person { public string Name; public int Age; }
- When you create an instance of a class, a reference to that instance is stored in the variable.
Person p = new Person();
String Type: Strings are immutable sequences of characters and are reference types in C#. They are stored on the heap.
Example:
string message = "Hello, World!";
- Although strings are reference types, they behave like value types in certain contexts (e.g., when comparing strings, it's based on the content, not reference).
Array Types: Arrays are collections of variables of the same type, stored in contiguous memory locations. Arrays are reference types.
Example:
int[] numbers = new int[5]; string[] names = { "Alice", "Bob", "Charlie" };
Interface Types: Interfaces define a contract that classes can implement. They specify methods or properties but do not provide implementation.
Example:
interface IMovable { void Move(); }
Delegate Types: A delegate is a type that references methods with a specific parameter list and return type. Delegates are used for implementing callbacks or event-driven programming.
Example:
delegate void PrintMessage(string message);
Nullable Types
By default, value types cannot be assigned null
in C#. However, C# provides nullable value types (for example, int?
) which can store either a value or null
. This is useful when you want to represent undefined or missing values.
Example:
int? nullableInt = null;
if (nullableInt.HasValue)
{
Console.WriteLine(nullableInt.Value);
}
else
{
Console.WriteLine("No value assigned.");
}
Implicit and Explicit Type Declaration
Explicit Declaration: You declare the variable with its specific type.
int age = 30; double price = 19.99;
Implicit Declaration: You use the
var
keyword to let the compiler infer the type based on the assigned value.var age = 30; // inferred as int var name = "Alice"; // inferred as string
Type Conversion
C# provides two types of conversions between data types:
Implicit Conversion: Automatic conversion between compatible types (e.g.,
int
tofloat
).Example:
int num = 10; float f = num; // implicit conversion
Explicit Conversion (Casting): Manual conversion using a cast when the types are not compatible automatically.
Example:
double d = 9.78; int i = (int)d; // explicit conversion (casting)
You can also use methods like Convert.ToInt32()
, Convert.ToString()
, etc., for conversions.
Summary of C# Data Types:
- Value Types: Store actual data directly (e.g.,
int
,float
,bool
,structs
,enums
). They are stored on the stack. - Reference Types: Store a reference to the data, which is stored on the heap (e.g.,
classes
,strings
,arrays
,interfaces
,delegates
). - Nullable Types: Allow value types to store
null
values (e.g.,int?
). - Type Conversion: Includes implicit (automatic) and explicit (manual) type conversions.
Understanding C# data types is crucial because it helps you manage memory and optimize program performance, while ensuring type safety throughout your code.