C# Basics/

Data Types

Original YouTube Logo

This page have a related YouTube video

  • C# has two main categories of data types: value types and reference types.
  • Common value types in C# include int, double, bool, and char.
  • Common reference types in C# include string and object.
  • C# is a statically-typed language, which means that the data type of a variable must be specified when it is declared ('var' can be used to let it figure it out by itself), and it cannot be changed later.

In C#, a data type is a classification of types of data that determine the possible values and operations that can be performed on that data. There are two main categories of data types in C#: value types and reference types.

Value Types

Value types are data types that store values directly. Some common value types in C# include:

  • int (integer): stores whole numbers, such as 1, 0, or -100
  • double (floating point number): stores numbers with decimal points, such as 3.14 or 0.001
  • bool (boolean): stores true or false values
  • char (character): stores a single character, such as 'a' or 'Z'

To declare a variable with a value type in C#, you use the following syntax:

For example, to declare an integer variable called "age" and assign it a value of 30, you would use the following code:

Reference Types

Reference types are data types that store a reference to the location of the value. Some common reference types in C# include:

  • string (text): stores a sequence of characters, such as "Hello, world!"
  • object: a generic type that can store any value

To declare a variable with a reference type in C#, you use the same syntax as with value types:

For example, to declare a string variable called "name" and assign it a value of "John", you would use the following code:

It's important to choose the appropriate data type for your variables in C#, as it affects the values that can be stored in the variable and the operations that can be performed on it. Choosing the wrong data type can lead to errors and unexpected results in your code.

It's also important to note that C# is a statically-typed language, which means that the data type of a variable must be specified when it is declared, and it cannot be changed later. This is in contrast to dynamically-typed languages, where the data type of a variable is determined at runtime.

In C#, you can use the var keyword to let the compiler infer the data type of a variable from the value being assigned to it. For example:

In this case, the compiler will infer that name is a string because it is being assigned a string value. However, it's generally a good idea to explicitly specify the data type of your variables to make your code more readable and maintainable.

}

ZetBit

Subscribe to ZetBits Newsletter