# Variables and Types

## Variables and Types

C# is a statically-typed language. Therefore, we must define the types of variables before using them.

To define a variable in C#, we use the following syntax, which is similar to C / Java:

```csharp
int myInt = 1;
float myFloat = 1f;
bool myBoolean = true;
string myName = "John";
char myChar = 'a';
double myDouble = 1.75;
```

Notice that defining a floating-point number requires an explicit `f` letter after the number.

### var keyword

C# supports `var` keyword - which means that you don't always have to explicitly specify a type - you can let the compiler try and understand the type of variable automatically. However, once the type of variable has been determined, it cannot be assigned a different type:

```csharp
var x = 1;
var y = 2;
var sum = x + y;    // sum will also be defined as an integer
```

### Exercise

Define three variables:

A `string` named productName equal to *TV*

An `int` named productYear equal to *2012*

A `float` named productPrice equal to *279.99f*

```csharp
using System;

public class Program
{
   public static void Main()
   {
      // write your code here
      
      // Do not modify code below!
      Console.WriteLine("productName: " + productName);
      Console.WriteLine("productYear: " + productYear);
      Console.WriteLine("productPrice: " + productPrice);

   }
}
```

## Type Conversion

C# types are not the same! In some cases, you have to convert a value's type. There are two methods:

* By explicitly casting it: `int x = (int) 1.0;`
* By using methods: `int y = Convert.ToInt32(1.0);`

{% hint style="info" %}
Read more on official [documentation](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions)
{% endhint %}

### Exercise

Convert myDBL to int and print it.

```csharp
using System;

public class Program
{
    public static void Main()
    {
        double myDBL = 99.0;
    
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://raviram.gitbook.io/c-programing/c-fundamental-concepts/variables-and-types.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
