> For the complete documentation index, see [llms.txt](https://raviram.gitbook.io/c-programing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://raviram.gitbook.io/c-programing/c-fundamental-concepts/variables-and-types.md).

# 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;
    
    }
}
```
