Auto keyword and when to use it

JN 666total at wp.pl
Mon Aug 20 17:42:12 UTC 2018


On Monday, 20 August 2018 at 17:24:19 UTC, QueenSvetlana wrote:
> I'm new to D programming, but have I have a background with 
> Python.
>
> I'm struggling to understand what the auto keyword is for and 
> it's appropriate uses. From research, it seems to share the 
> same capabilities as the var keyword in C#. From the C# 
> documentation, it states:
>
> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var
>
> ... variables that are declared at method scope can have an 
> implicit "type" var. An implicitly typed local variable is 
> strongly typed just as if you had declared the type yourself, 
> but the compiler determines the type.
>
> Is the same true for auto? For example, if I have a class 
> Person, I might have attributes such as FirstName, LastName 
> which should obviously be strings but will D allow me to 
> declare class level attributes with auto?
>
> C# doesn't allow this.

It basically works like C#.

auto x = "hi";

will make x a string.

But if you later try:

x = 5;

it will throw an error, because x is a string. It's used to save 
you the typing of the type, it doesn't make the language 
dynamically typed.


More information about the Digitalmars-d-learn mailing list