What is the .stringof property in D language?

Overview

In D, all datatypes, symbols, and expressions have properties that can be checked. In this shot, we’ll look at the .stringof property.

What is the stringof property?

With the .stringof property, a constant string is produced as output. This string is only a representation of the identifier that prefixes the .stringof property statement. This means it cannot be used for computational purposes because it is only a string.

This property is one of the common properties for types, symbols, and expressions. It is used to convert the name or values of these types, symbols, and expressions to strings.

For types, .stringof makes the string of the type. For example, int.stringof produces “int”.

For expressions and symbols, they become strings and only a representation of them. This means such values cannot be used in evaluations.

To get the string of any type, symbol, or expression, we have to prefix them to the .stringof property, as shown below:

Syntax

X.stringof

Where X is the type, expression or symbol.

Code example

import std.stdio;
struct House { }
enum Shoes { Men }
int myint = 4;
void main()
{
//print the string of the struc House
writeln(House.stringof); // "House"
//convert shoe.Men enum type to string using strinof
string hold = (Shoes.Men.stringof);
// check the new typeof shoe.Men enum in hold and display
writeln(typeof(hold).stringof); // "string"
//display the string form of the int identifier
writeln(myint.stringof); // myint
//change myint type to string and display type string as srting
writeln(typeof(myint.stringof).stringof); //"string"
}

Explanation

  • Line 1: We import a package.

  • Lines 2–4: We define variables.

  • Lines 6–18: We define the main function.

  • Lines 9–17: We use the .stringof property to convert types and expressions to a string. Next, we print the results to display along with explanatory inline comments.

Note: The .stringof method also converts the datatype of variables, which can be saved in another variable of type string.

Free Resources