Variable

English:

Variable

Storage values is normal practice while you are programming.
Remember about the example when our code checks the user's age.
The user should enter this information (Input) and code will execute the verification about that data.
But... Where this value (age) will be storaged after user's input?
To storage values in code, the world of progammation has one principle called variable.
Variables are memory spaces in your computer that can "hold" or "storage" values.
Think about one shelf with some boxes and inside of these boxes theres random things.
Memory space on your computer is the shelf, boxes are variables and storage inside (things) are values to use.
If you want to something inside box, you can open it up and get that thing. This You know where find that box.
Then, analogy, if you want use some value in your code, you can store it in variable and can recover it to use after.
To declare a variable you must define two information to the compiler:

Type data and identifiers.

C# is a strongly typed language, it means that variables can only store data from a specific type.
This type is known by the compiler at compilation time and runtime.

Most important types are:

Numerical:
Int -> Numerical integer values (0, 45, -9)
Float -> Numerical decimal value (5.7)
Double -> Also decimal value, but with more precision in floating point (3.14)

Text/character types:
String -> Text data type ("Hey friend") 
*STRINGS ARE DEFINED BETWEEN DOUBLE QUOTES

Char -> Storage only one character '$'*
*CHARS TYPES ARE ALWAYS DEFINED BETWEEN QUOTES

Logical:
Bool -> Storage only two possible values: true or false (like binary principle)

Enumeration:
Enum -> Define a bunch of fixed values.

There is another more specific data type in C#, however, these are most usable.
Other information to declare variables is the identifier.
The programmer should to choice this identifier, that is just a "name" of variable, how it will referenced among the code.
If you have one code that storage user's name, declare one variable string data type and you can name it like  "name", for example.

string name;

This is a way to declare variables in C#.

Alert Warning: Never start identifiers with numbers (4variable), don't use special characters (var##) unless "_" character (my_variable), reserved C# keywords as "string" (If you want to do that, use @ symbol) eg: @string, and the space to split names (car color) instead of, do this way (carColor) with CamelCase notation (first word lower case and another with upper case)
As you know, variables work to storage some data, right? About that, now you have declared one variable, some value of that data type must be storaged in.

To storage values of variables, we use the assignment operator (=) and the value that you want to hold. Eg:

string name = "Dennis";
*REMEBER THAT TO STORAGE IN STRINGS DATA TYPE, THIS VALUE MUST BE BETWEEN DOUBLE QUOTES!

Assingmenting in strings and char type:

string country = "Sweden";
string favoriteColor = "Purple";
string message = "Hey you, I'm learning about variables at this moment!";

char secretNumber = '5';
char specialChar = '@';

Numerical data type:
int amountFruits = 40;
int temperature = -20;
double piValue = 3.1415926;
float price = 5.99F;
float height = 1.92F;

*TO STORAGE IN FLOAT DATA TYPE, PUT "F" AT END OF VALUE.

Boolean type:
bool isOn = true;

You also are able to storage what user input with Console. ReadLine:
string favoriteColor = ConsoleReadLine ();
If I input "Red", at this moment the variable "favoriteColor" will storage this value.
Console. ReadLine only returns string data type, then if you want to store numerical values, you must force conversion to that data type. 

The commands to convertion numerical values are int.Parse(), float.Parse(), Convert.ToDouble().
Between parenthesis enter which value would be converted, in this case, what Console.ReadLine is holding.

int amountFruits = int.Parse(Console.ReadLine());

float price = float.Parse(Console.ReadLine());

double piValue = Convert.ToDouble(Console.ReadLine());

Nested commands are a normal practice, get used to them.

Português-BR:

Variável

Armazenar valores é uma prática normal enquanto você está programando.
Lembre-se do exemplo em que nosso código verifica a idade do usuário.
O usuário deve inserir essas informações (entrada) e o código executará a verificação sobre esses dados.
Mas ... Onde esse valor (idade) será armazenado após a entrada do usuário?
Para armazenar valores no código, o mundo da programação tem um princípio chamado variável.
Variáveis ​​são espaços de memória no seu computador que podem "reter" ou "armazenar" valores.
Pense em uma prateleira com algumas caixas e dentro dessas caixas há coisas aleatórias.
A memória do seu computador é a prateleira, as caixas são variáveis ​​e o armazenamento interno (itens) são valores a serem usados.
Se você quiser algo dentro da caixa, pode abri-la e obter essa coisa. Você sabe exatamente onde encontrar essa caixa.
Então, por analogia, se você quiser usar algum valor no seu código, poderá armazená-lo na variável e recuperá-lo para usar depois.
Para declarar uma variável, você deve definir duas informações para o compilador:

Tipo de dados e identificadores.

C # é uma linguagem fortemente tipada, isso significa que as variáveis ​​podem armazenar apenas dados de um tipo específico.
Esse tipo é conhecido pelo compilador no momento da compilação e no tempo de execução.

Os principais tipos são:

Numérico:
Int -> Valores inteiros numéricos (0, 45, -9)
Float -> valor decimal numérico (5,7)
Double -> também valor decimal, mas com mais precisão no ponto flutuante (3.14)

Tipos de texto / caracteres:
String -> Tipo de dados de texto ("Olá amigo")
* AS STRINGS SÃO DEFINIDAS ENTRE CITAÇÕES DUPLAS

Char -> Armazena apenas um caractere '$' *
* TIPOS DE CHARS SÃO SEMPRE DEFINIDOS ENTRE CITAÇÕES SIMPLES

Lógico:
Bool -> Armazena apenas dois valores possíveis: verdadeiro ou falso (como princípio binário)

Enumeração:
Enum -> Defina um monte de valores fixos.

Há outros tipos de dados mais específico em C #, no entanto, esses são os mais utilizáveis.
Outra informação para declarar variáveis ​​é o identificador.
O programador deve escolher esse identificador, que é apenas um "nome" da variável, como será referenciado no código.
Se você tiver um código que armazene o nome do usuário, declare o tipo de dados da  variável como "string" e poderá nomeá-la como "nome", por exemplo.

string nome;

Esta é uma maneira de declarar variáveis ​​em C #.

Alerta de aviso: nunca inicie identificadores com números (4variable), não use caracteres especiais (var##) e acentos, a menos o caractere "_" (minha_variavel), palavras-chave em C# como "string" (se você quiser fazer isso, use o símbolo @ ), por exemplo: @string, e o espaço para dividir nomes é proibído (cor do carro) em vez disso, faça desta maneira (corDoCarro) com a notação CamelCase (primeira palavra em minúscula e as outras em maiúsculas)
Como você sabe, as variáveis ​​trabalham para armazenar dados, certo? Sobre isso, agora que você declarou uma variável, é necessário armazenar algum valor desse tipo de dados.

Para armazenar valores em variáveis, usamos o operador de atribuição (=) e o valor que você deseja manter. Por exemplo:

string nome = "Dennis";
* LEMBRE-SE DE QUE ARMAZENAR EM TIPOS DE DADOS DE STRINGS, ESTE VALOR DEVE ESTAR ENTRE CITAÇÕES DUPLAS!

Armazenando em tipos String e Char:

string pais = "Suécia";
string corFavorita = "Roxo";
string mensagem = "Ei você, estou aprendendo sobre variáveis ​​neste momento!";

char numeroSecreto = '5';
char charEspecial = '@';

Tipo de dados numéricos:
int quantidadeDeFrutas = 40;
int  temperatura = -20;
double piValor = 3,1415926;
float preco = 5,99F;
float altura = 1,92F;

* PARA ARMAZENAR NO TIPO DE DADOS FLOAT, COLOQUE "F" NO FIM DO VALOR.

Tipo booleano:
bool estaLigado = true;

Você também pode armazenar qual a entrada do usuário com o Console.ReadLine()

string favoriteColor = ConsoleReadLine ();

Se eu inserir "Red", neste momento a variável "favoriteColor" armazenará esse valor.
O Console.ReadLine retorna apenas o tipo de dados string, se você deseja armazenar valores numéricos, deve forçar a conversão para esse tipo de dados. 

Os comandos para converter valores numéricos são int.Parse (), float.Parse (), Convert.ToDouble ().
Entre parênteses, digite qual valor seria convertido, nesse caso, o que Console.ReadLine está mantendo.

int quantidadeDeFrutas = int.Parse (Console.ReadLine ());

floar preco = float.Parse (Console.ReadLine ());

double piValor = Convert.ToDouble (Console.ReadLine ());

Comandos aninhados são uma prática normal, acostume-se a eles.

Comentários

Postagens mais visitadas deste blog

Boolean type

Assignments Operators

Increment and decrement operations