GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — C# - Data Types
Selected Reading
C# - Data TypesIntroduction to C# Data TypesC# data types define the type of data a variable can store, such as integers, floating-point numbers, characters, or Boolean values. The data types are essential to declare specific variables to store the related value, memory optimization, performance improvements, and code readability. In this chapter, you will learn:
What Are Data Types in C#?C# data types specify the type of data that variables can store. In C#, all variables must be declared with the data types before their use, as it is a strongly typed language. Syntax for Declaring a Variable with Data Type<data_type> <variable_name> = <value>; Example of C# Data Typesusing System;
class Program
{
static void Main()
{
string studentName = "Sudhir Sharma";
int studentAge = 20;
double marksPercentage = 85.5;
char grade = 'A';
bool isEnrolled = true;
Console.WriteLine("Student Name: " + studentName);
Console.WriteLine("Age: " + studentAge);
Console.WriteLine("Marks Percentage: " + marksPercentage + "%");
Console.WriteLine("Grade: " + grade);
Console.WriteLine("Enrolled: " + isEnrolled);
}
}
This example will produce the following output: Student Name: Sudhir Sharma Age: 20 Marks Percentage: 85.5% Grade: A Enrolled: True Types of Data in C#The variables in C#, are categorized into the following types −
1. Value Types in C#Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. Value types store actual values and include:
Integral Data Types
Exampleusing System;
class Program
{
static void Main()
{
int studentID = 1024;
long salary = 5000000L;
byte experienceYears = 10;
Console.WriteLine("Student ID: " + studentID);
Console.WriteLine("Employee Salary: " + salary);
Console.WriteLine("Experience (Years): " + experienceYears);
}
}
This example will produce the following output: Student ID: 1024 Employee Salary: 5000000 Experience (Years): 10 Floating-Point Data Types
Exampleusing System;
class Program
{
static void Main()
{
float gpa = 3.85f;
double distance = 384400.5;
decimal accountBalance = 15249.75m;
Console.WriteLine("Student GPA: " + gpa);
Console.WriteLine("Distance to Moon (km): " + distance);
Console.WriteLine("Bank Account Balance: $" + accountBalance);
}
}
This example will produce the following output: Student GPA: 3.85 Distance to Moon (km): 384400.5 Bank Account Balance: $15249.75 Use Use Character and Boolean Data Types
Exampleusing System;
class Program
{
static void Main()
{
bool isGraduate = true;
char section = 'B';
Console.WriteLine("Graduated: " + isGraduate);
Console.WriteLine("Class Section: " + section);
}
}
This example will produce the following output: Graduated: True Class Section: B Enumerations (enum)An Exampleusing System;
class Program
{
enum JobLevel { Intern, Junior, Mid, Senior, Manager }
static void Main()
{
JobLevel currentLevel = JobLevel.Mid;
Console.WriteLine("Current Job Level: " + currentLevel);
}
}
This example will produce the following output: Current Job Level: Mid StructsA Exampleusing System;
struct Employee
{
public int ID;
public string Name;
public double Salary;
}
class Program
{
static void Main()
{
Employee emp;
emp.ID = 101;
emp.Name = "Zoya";
emp.Salary = 60000.50;
Console.WriteLine("Employee ID: " + emp.ID);
Console.WriteLine("Employee Name: " + emp.Name);
Console.WriteLine("Employee Salary: $" + emp.Salary);
}
}
This example will produce the following output: Employee ID: 101 Employee Name: Zoya Employee Salary: $60000.5 2. Reference Types in C#The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic,, string, and array. Object TypeThe Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. object obj; obj = 100; // this is boxing Exampleusing System;
class Program
{
static void Main()
{
object obj = 1001; // Student ID
Console.WriteLine("Student ID: " + obj);
obj = "Sudhir Sharma"; // Student Name
Console.WriteLine("Student Name: " + obj);
}
}
This example will produce the following output: Student ID: 1001 Student Name: Sudhir Sharma Dynamic TypeYou can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is − dynamic <variable_name> = value; Exampleusing System;
class Program
{
static void Main()
{
dynamic value = 10;
Console.WriteLine("Dynamic value: " + value);
value = "Hello, World!";
Console.WriteLine("Dynamic now contains: " + value);
}
}
This example will produce the following output: Dynamic value: 10 Dynamic now contains: Hello, World! Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time. String TypeThe String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted. Exampleusing System;
class Program
{
static void Main()
{
string firstName = "Sudhir";
string lastName = "Sharma";
string fullName = firstName + " " + lastName;
Console.WriteLine("Full Name: " + fullName);
}
}
This example will produce the following output: Full Name: Sudhir Sharma Note: Use StringBuilder for modifying strings efficiently. A @quoted string literal looks as follows − @"Tutorials Point"; The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter. Array TypeArrays store multiple values of the same type in a single variable. Exampleusing System;
class Program
{
static void Main()
{
string[] students = { "Zoya", "Yashna", "Olivia", "Naomi" };
Console.WriteLine("Student List:");
foreach (string student in students)
{
Console.WriteLine(student);
}
}
}
This example will produce the following output: Student List: Zoya Yashna Olivia Naomi 3. Pointer Type in C#Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++. Syntax for declaring a pointer type is − type* identifier; Exampleusing System;
unsafe class Program
{
static void Main()
{
int grade = 90;
int* ptr = &grade;
Console.WriteLine("Original Grade: " + grade);
Console.WriteLine("Memory Address: " + (ulong)ptr);
*ptr = 95; // Modifying value using pointer
Console.WriteLine("Updated Grade: " + grade);
}
}
This example will produce the following output: main.cs(3,1): error CS0227: Unsafe code requires the `unsafe' command line option to be specified Compilation failed: 1 error(s), 0 warnings Type Conversion in C#There may be situations where you need to change the type of a variable. Type conversion allows you to convert data from one type to another. In C#, there are two types of type conversions: implicit and explicit. 1. Implicit Conversion (Safe)Implicit conversion occurs automatically when there is no risk of data loss. C# allows implicit conversion for compatible types. Exampleusing System;
class Program
{
static void Main()
{
int studentAge = 18;
double preciseAge = studentAge; // Implicit conversion
Console.WriteLine("Student Age (Integer): " + studentAge);
Console.WriteLine("Converted to Double: " + preciseAge);
}
}
This example will produce the following output: Student Age (Integer): 18 Converted to Double: 18 2. Explicit Conversion (Casting)Explicit conversion is required when converting between incompatible types. This is done using casting. Exampleusing System;
class Program
{
static void Main()
{
double salary = 50000.75;
int roundedSalary = (int)salary; // Explicit casting
Console.WriteLine("Original Salary (Double): " + salary);
Console.WriteLine("Rounded Salary (Integer): " + roundedSalary);
}
}
This example will produce the following output: Original Salary (Double): 50000.75 Rounded Salary (Integer): 50000 Best Practices for Using Data Types in C#
Common Mistakes to Avoid1. Using an Incorrect Data Type// Error: Should use `decimal` float price = 100.99f; Fix: Use decimal price = 100.99m; 2. Not Handling Null Values in Reference Types// This will cause a NullReferenceException string name; Console.WriteLine(name.Length); Fix: Always initialize strings before using them. string name = "sudhir"; Console.WriteLine(name.Length); 3. Ignoring Type Compatibility in Assignments// Compilation error: Cannot assign a string to an int int age = "25"; Fix: Convert the string properly before assigning it to an integer. int age = int.Parse("25"); // or Convert.ToInt32("25")
FAQ About C# Data TypesQ1: What is the difference between float, double, and decimal?
Q2: Can I store an integer in a char variable?No, but you can cast an integer to a char: char c = (char)65; // Outputs 'A' Q3: What is the best way to store large numbers?Use long for large integers and double for large floating-point values. Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |