Saltar al pie de página
.NET AYUDA

Tipos de C# (Cómo funciona para desarrolladores)

In any programming language, understanding data types is crucial, and C# is no different. Whether it's the int type or the floating-point type, each type holds a particular kind of information, also known as actual data.

The Basics of C#

C# is a strongly typed language. But what does strongly-typed language mean, you ask? It means that every variable and object must have a declared data type. And it's the data type that determines what kind of data you can store in that variable.

C# has two major data types: value types and reference types. These are also the user-defined types you might hear about.

Value Types in C#

In C#, value types are simple. When you declare a value type variable, the actual data stored is the value that you assign to the variable. If you change the value of one variable, it doesn't affect any other variable.

The most common value types in C# include:

  • Integers (represented by the int type)
  • Floating-point numbers (represented by the float and double types)
  • Boolean, which is either true or false

Let's talk about the int type first. An int type in C# is a 32-bit data type that can store whole numbers from -2,147,483,648 to 2,147,483,647. Here's an example:

int myInteger = 15;
int myInteger = 15;
Dim myInteger As Integer = 15
$vbLabelText   $csharpLabel

Now, onto the floating-point type. In C#, there are two floating-point types: float and double.

The float type is a 32-bit floating-point number with precision up to 7 digits. It's great for scientific calculations. A float type variable can be declared like this:

float myFloat = 12.34F;
float myFloat = 12.34F;
Dim myFloat As Single = 12.34F
$vbLabelText   $csharpLabel

The double type is a 64-bit floating-point type with precision up to 15-16 digits. It's more accurate than the float type and is often used for financial and monetary calculations. Here's an example of a double type variable:

double myDouble = 12.3456789;
double myDouble = 12.3456789;
Dim myDouble As Double = 12.3456789
$vbLabelText   $csharpLabel

Predefined Data Types in C#

Alright, moving on. C# provides several "predefined data types" that you can use in your applications. These are the fundamental building blocks that you can use to define your own "user-defined types."

Here are a few examples:

  • byte: This is an 8-bit unsigned integer that ranges from 0 to 255.
  • char: It's a 16-bit Unicode character.
  • decimal: Ideal for financial and monetary calculations because of its high precision.
  • bool: Stores either true or false, perfect for logical operations.

Each of these "predefined data types" has its own purpose and its own "default value," so it's important to choose the right one for your needs!

Default Values in C#

In C#, each data type comes with a default value. For value type variables, if you don't initialize them, they automatically take their default value.

For instance, the default value of an int type is 0, and the default value of a floating-point value type (either float or double) is 0.0.

The default value for reference types is null, indicating that it's not referencing any object.

Type Conversion in C#

Sometimes, you may need to convert one data type to another. This is known as type conversion, and C# supports two kinds: implicit conversion and explicit conversion.

Implicit conversion happens automatically when you assign a value of one type to a variable of a compatible type that can hold larger values. For instance, you can assign an int type to a double type without losing information.

int myInt = 10;
double myDouble = myInt; // Implicit conversion
int myInt = 10;
double myDouble = myInt; // Implicit conversion
Dim myInt As Integer = 10
Dim myDouble As Double = myInt ' Implicit conversion
$vbLabelText   $csharpLabel

Explicit conversion, also known as casting, is required when you're trying to convert between incompatible types, or from larger types to smaller ones. It's done by placing the target type in parentheses in front of the value to be converted.

double myDouble = 10.5; 
int myInt = (int)myDouble; // Explicit conversion, decimal part is lost
double myDouble = 10.5; 
int myInt = (int)myDouble; // Explicit conversion, decimal part is lost
Imports System

Dim myDouble As Double = 10.5
Dim myInt As Integer = CInt(Math.Truncate(myDouble)) ' Explicit conversion, decimal part is lost
$vbLabelText   $csharpLabel

Reference Types in C#

The reference types in C# work a bit differently from value types. Instead of storing the actual data, a reference type variable stores the address where the value is being stored. In other words, it 'refers' to another location in memory.

So, if you change the reference type object, it affects the other variable as well. This is because the reference type variable automatically reflects changes made to the actual data stored at the memory address it points to.

Now, that might sound a little complex, but let's break it down with an example. Let's say we have a class called Person:

class Person
{
    public string Name { get; set; }
}
class Person
{
    public string Name { get; set; }
}
Friend Class Person
	Public Property Name() As String
End Class
$vbLabelText   $csharpLabel

And then we create two "reference type" variables of this class:

Person person1 = new Person { Name = "Alice" };
Person person2 = person1;
Person person1 = new Person { Name = "Alice" };
Person person2 = person1;
Dim person1 As New Person With {.Name = "Alice"}
Dim person2 As Person = person1
$vbLabelText   $csharpLabel

Here, both person1 and person2 are pointing to the same memory location. If we change person1, person2 will reflect that change:

person1.Name = "Bob"; 
Console.WriteLine(person2.Name); // Outputs "Bob"
person1.Name = "Bob"; 
Console.WriteLine(person2.Name); // Outputs "Bob"
person1.Name = "Bob"
Console.WriteLine(person2.Name) ' Outputs "Bob"
$vbLabelText   $csharpLabel

Arrays in C#

An array is a reference type that holds multiple values of the same data type. It's like a container where you can store a collection of values, all of which are of the same type.

To declare an array, you first specify the data type of its elements, followed by square brackets. Then you use the new keyword to create the array and specify its length.

int[] myIntArray = new int[5]; // Array of int type, can hold 5 values
int[] myIntArray = new int[5]; // Array of int type, can hold 5 values
Dim myIntArray(4) As Integer ' Array of int type, can hold 5 values
$vbLabelText   $csharpLabel

To access the elements of the array, you use an index, starting at 0 for the first element.

myIntArray[0] = 10; // Sets the first element of the array to 10
myIntArray[0] = 10; // Sets the first element of the array to 10
myIntArray(0) = 10 ' Sets the first element of the array to 10
$vbLabelText   $csharpLabel

Remember, arrays in C# are "reference types," so changes made in one variable will affect any "other variable" referencing the same array.

Generating PDFs with IronPDF in C#

IronPDF is a powerful library for C# that allows developers to create, edit, and extract content from PDFs. This can be a lifesaver for tasks like generating reports or creating dynamic invoices.

Getting Started with IronPDF

First, you'll need to install IronPDF. You can do this through NuGet, a popular package manager for .NET. Run the following command in your package manager console:

Install-Package IronPdf

Creating a PDF from HTML

IronPDF is able to create PDFs from HTML. It's pretty straightforward:

using IronPdf;

var Renderer = new ChromePdfRenderer();
Renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>").SaveAs("HelloWorld.pdf");
using IronPdf;

var Renderer = new ChromePdfRenderer();
Renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>").SaveAs("HelloWorld.pdf");
Imports IronPdf

Private Renderer = New ChromePdfRenderer()
Renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>").SaveAs("HelloWorld.pdf")
$vbLabelText   $csharpLabel

The above code will generate a PDF with the "Hello, World!" heading. Notice that the HTML code is simply a string. In C#, a string is a reference type, and it's one of the most used C# types.

C# Types (How It Works For Developers) Figure 1 - Hello World text

Conclusion

Congratulations! You've taken a deep dive into the world of C# Types, understanding value types, reference types, predefined data types, and how they shape the way you write code. You've also seen the power of using libraries like IronPDF.

IronPDF offers a free trial and licenses for IronPDF start from $liteLicensing.

Preguntas Frecuentes

¿Qué significa que C# es un lenguaje fuertemente tipado?

C# es un lenguaje fuertemente tipado, lo que significa que cada variable y objeto debe tener un tipo de dato declarado, lo que determina qué tipo de datos se puede almacenar. Esto garantiza la seguridad y coherencia de tipos al usar bibliotecas como IronPDF para manejar datos.

¿Cómo puedo convertir HTML a PDF en C#?

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas de HTML en PDFs. También puedes convertir archivos HTML a PDFs usando RenderHtmlFileAsPdf.

¿Qué son los tipos de valor en C#?

Los tipos de valor en C# almacenan los datos reales que se les asignan. Ejemplos comunes incluyen enteros (int), números de punto flotante (float y double) y booleanos (bool). Estos tipos son útiles cuando se usa IronPDF para tareas de procesamiento de datos.

¿Cuál es el propósito de los tipos de referencia en C#?

Los tipos de referencia en C# almacenan la dirección de donde se encuentra realmente los datos en la memoria. Esto es crucial al usar bibliotecas como IronPDF, ya que los cambios en una variable pueden afectar a otra si hacen referencia a los mismos datos.

¿Cómo se realiza una conversión de tipo implícita en C#?

La conversión de tipo implícita en C# ocurre automáticamente cuando se asigna un valor de un tipo a un tipo compatible que puede contener valores más grandes. Por ejemplo, convertir un int a un double se hace automáticamente, lo cual podría encontrarse al trabajar con IronPDF.

¿Puedes dar un ejemplo de conversión de tipo explícita en C#?

La conversión de tipo explícita, o cast, es necesaria en C# al convertir entre tipos no compatibles, como convertir un double a un int. Esto se hace colocando el tipo de destino entre paréntesis frente al valor, un método que también se puede aplicar al usar IronPDF para manejo de datos especializado.

¿Cómo se utilizan las matrices en C#?

Las matrices en C# son tipos de referencia que pueden almacenar múltiples valores del mismo tipo de dato. Se declaran especificando el tipo de dato, seguido de corchetes, y se usa la palabra clave new para crear la matriz y especificar su longitud. Este concepto es útil al manejar grandes conjuntos de datos con IronPDF.

¿Cómo puedo crear un PDF desde HTML usando una biblioteca en C#?

IronPDF es una poderosa biblioteca de C# que permite a los desarrolladores crear PDFs desde HTML. Mediante el uso de métodos como RenderHtmlAsPdf, puedes generar fácilmente PDFs directamente desde contenido HTML.

¿Cuáles son los beneficios de usar IronPDF para la manipulación de PDF en C#?

IronPDF proporciona un robusto conjunto de características para crear, editar y extraer contenido de PDFs en C#. Soporta la conversión de HTML a PDF, agregar encabezados y pies de página, y más, convirtiéndolo en una herramienta esencial para desarrolladores que trabajan con documentos PDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más