Knowledge varieties in C# are fundamental programming ideas that outline what sort of knowledge a variable can maintain. C# is a statistically-typed language, and, as such, each variable needs to be declared with a particular information sort previous to getting used. On this programming tutorial, we are going to focus on the completely different information varieties that C# has to supply, together with the built-in information varieties and reference varieties. We may also cowl the idea of sort conversion and showcase some code examples displaying their utilization.
Bounce to:
What are Knowledge Sorts in C#?
As famous in our introduction, information varieties denote the kind of info a variable can maintain, equivalent to a string or numeric worth. Additional, additionally they outline the vary of values the variable can maintain and the sorts of operations that may be carried out on the variable. As an example, you wouldn’t carry out calculations on a textual content worth, nor would you capitalize a quantity.
C# information varieties are roughly categorized into two foremost classes: worth varieties and reference varieties
. We are going to focus on every of those information varieties within the sections under. However first, let’s focus on the advantages of utilizing information varieties in our C# applications.
Learn: JetBrains ReSharper IDE Overview
Advantages of Utilizing Knowledge Sorts
Apart from being a mandatory ingredient to any software a developer builds, information varieties additionally supply the next advantages:
- Enhances reminiscence effectivity: By allocating the correct reminiscence for variables based mostly upon their information sort, we make our reminiscence utilization extra environment friendly, leading to higher efficiency
- Sort security: Utilizing information varieties allows programmers to catch type-related errors at compile-time versus runtime
- Higher code readability: Defining our information varieties helps make clear their supposed use and function, mitigating the probabilities of misuse.
Now that we perceive a number of the core advantages of utilizing C# information varieties, we are able to focus on the differing types out there to make use of.
Constructed-in C# Knowledge Sorts
C# has a number of types of built-in varieties, together with:
- Numeric varieties
- Character varieties
- Boolean varieties
- Integer varieties
- Structs
Numeric Sorts in C#
C# gives quite a lot of numeric varieties. They embody:
- byte and sbyte: Used for 8-bit signed and unsigned integers.
- quick and ushort: Used for 16-bit signed and unsigned integers
- int and uint: Used for 32-bit signed and unsigned integers. Holds values from -2,147,483,648 to 2,147,483,647.
- lengthy and ulong: Used for 64-bit signed and unsigned integers. Holds values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808
- float: Used for 32-bit floating-point numbers. Holds values as much as 7 decimals.
- double: Used for 64-bit double-precision floating-point numbers. Holds values as much as 15 decimals.
- decimal: 128-bit decimal floating-point numbers
For starters, integer information varieties are used to characterize entire numbers. There are a number of sorts of integers, together with byte, quick, int,, and lengthy. Every sort of integer holds a sure sort of numeric worth, proven in our listing above. To outline a fundamental int and assign it a worth, we use the next syntax:
int age = 20;
If we needed to create a protracted and assign it a worth, we might use the next code instance:
lengthy earthAge = 400000000L;
Floating-point varieties, in the meantime, characterize numbers with decimal factors or which can be fractional. Floating level varieties embody float, double, and decimal. If we needed to create a floating level sort of float, we might achieve this within the following method
: float myHeight = 6.5F;
Character and String Sorts in C#
For single unicode characters, C# depends on the char. The syntax to declare a char variable may be seen within the following code instance:
char check;
To assign a worth to a char, merely enclose the worth in citation marks, as proven under:
char check = ‘A’;
If you wish to create a variable able to holding greater than a single unicode character, it would be best to create a string sort. string varieties can maintain wherever from 1 to a billion characters. They’re usually used to carry phrases, sentences, and even paragraphs of text-based information. Right here is the syntax for making a string in C#:
string identify =”Nicholas”;
It’s also possible to create a string utilizing the System.String class. The syntax is barely completely different – you need to use an uppercase String versus the lowercase model:
String name2 = “Nick”;
Which you select to make use of is as much as the programmer – neither alternative is flawed. We are going to focus on strings in higher element in an upcoming tutorial.
Learn: Rider IDE Overview
Boolean Sorts
The bool sort is used to characterize a boolean worth, both true or false in C# . They’re generally used when it’s essential carry out an motion relying upon whether or not one assertion or one other is true or false.
For instance, let’s say we need to determine if one quantity is bigger than one other. We are able to achieve this utilizing a bool expression. First, we create two integers, then use Console.WriteLine to print the results of our analysis to the display. Right here is a few pattern code demonstrating this:
int age1 = 20; int age2 = 50; Console.Writeline(age1 > age2); //returns False as a result of ag1 IS NOT higher than age 2
On this instance, we assign the age1 variable a worth of 20 and our age2 variable the worth of 50. We then ask if age1 is bigger than age2. Since it isn’t, our bool expression will return a false worth.
Integer Knowledge Sorts and Floating Level Sorts
We briefly considered the integer and floating level varieties in our listing of the completely different numeric varieties. Right here, we focus on them in higher element. For starters, integer information varieties are used to characterize entire numbers. There are a number of sorts of integers, together with byte, quick, int,, and lengthy.
Enumerations and Enums
In C#, enum defines named constants, that are values that can not be modified or which can be read-only. Builders use fixed after they intend for his or her information to by no means change and stay constant. Enum values are in a listing format and start with the primary entry beginning at worth 0 by default. The second merchandise within the listing could be worth 1, and so forth. For instance, let’s say you’ve got an enum that holds the times of week. You’d outline it on this method:
enum Days { Sunday, // index 0 Monday, // index 1 Tuesday, // index 2 Wednesday, index 3 Thursday, index 4 Friday, index 5 Saturday index 6 }
As soon as the values are assigned to an Enum, we are able to then assign the person values to a variable. To take action, we might use code much like the next:
Days right now = Days.Monday; Console.WriteLine(right now);
This is able to print “Monday” to the display.
Structs
Structs may be regarded as information buildings that teams information. They’re much like lessons however are worth varieties that may maintain constructors, constants, fields, strategies, operators, indexers, and extra. They’re helpful in the event you want a construction to carry information values that don’t depend on inheritance, equivalent to key-value pairs. For instance, let’s say we needed to carry the placement of a constructing based mostly on its longitude and latitude. We might achieve this in a Struct within the following method:
struct Location { public int x; public int y; }
Reference Sorts in C#
References varieties retailer a “reference” to precise information versus the precise worth itself. The reference shops the handle the place a worth is saved, which may be regarded as a pointer to a reminiscence location. References varieties are capable of retailer references to lessons, strings, arrays, and delegates
Reference varieties retailer references to the precise information on the heap. They embody lessons, strings, arrays, and delegates.
Sort Conversion in C#
There are two types of sort conversion in C#: implicit and specific. Implicit sort conversion enables you to mechanically convert from appropriate information varieties, equivalent to changing an int worth to a lengthy. Express sort conversion is required if you need to convert incompatible information varieties.
For instance, let’s say we need to move a smaller worth to a worth sort that holds a bigger worth. In our instance under, we are going to use implicit sort conversion (or casting) to move an int to a double:
int myWeight = 200; double myDoubleWeight = myWeight;
Since each information varieties are appropriate, the conversion from int to double is automated and we don’t want to put in writing any additional code to power the conversion.
Nevertheless, if we needed to carry out the reverse operation and assign a double to an int, we would wish to handbook solid the worth, as an int doesn’t settle for decimal values. When this conversion occurs, the numbers after the decimal level are eliminated and the floating level worth turns into an integer worth or entire quantity as a substitute. Right here is how that appears in code:
double myDoubleWeight = 200.58; int myWeight = (int) myDoubleWeight; Console.WriteLine(myDoubleWeight); Console.WriteLine(myWeight);
Discover how we place (int) earlier than myDoubleWeight. This code is the place we power the conversion from a double to an int. If we run this program, we get the next output:
200.58 200
Last Ideas on C# Knowledge Sorts
Understanding the completely different information varieties and the way they work is essential for creating environment friendly and error-free C# functions. This programming tutorial coated the fundamental built-in information varieties C# has to supply, in addition to its reference varieties. We additionally mentioned each implicit and specific sort conversions and sort casting.