16
The keyword var
allows me to declare typed variables, and allows variables to be defined implicitly.
Example: var i = 10;
The compiler will assume that my variable i
is of the whole type int
.
Therefore, because the compiler does not allow me to use the keyword var
for attribute statements within a class?
See this example for illustration:
class ClasseExemplo
{
public var atributo; //Este atributo poderia ser declarado de forma implícita.
public ClasseExemplo()
{
this.atributo = null;
}
}
The above example returns the following error:
Error 1 The type or namespace name 'var' could not be found (are you Missing a using Directive or an Assembly Reference?)
If this way I can’t declare an attribute that can be of any type, there could be another way to do this?
Today C# has the option of using the static type Dynamic, which would work in the desired way, but I do not see this as a good programming practice, because the object is open to receive any type of data (including complex objects) and the non-use of a contract can cause problems, for example if the user calls a non-existent method or attribute of the instantiated object, the compiler allows the call and compiles without errors, but in the execution it does not find and throws an exception. See Dynamic in the Microsoft documentation: https://msdn.microsoft.com/pt-br/library/dd264736.aspx
– Julio Borges
Doesn’t look like this is the way you want it.
– Maniero
Not to mention that as you would enter the return type of the method that returns
atributo
?Int
,String
? If a type attribute could be definedvar
in the class, automatically it could not have methods that return it.– Guilherme Lautert
@Guilhermelautert would have to be
dynamic
. But in fact thedynamic
can be converted to a static type, of course it would no longer be the class field.– Maniero
@bigown Exactly, why would not logica use
var
in a class.– Guilherme Lautert