Tour: Basics
G# programs are organized into packages, can import CLR namespaces, and can use top-level statements for small executables.
// file: HelloWorld.gs
package HelloWorld
import System
Console.WriteLine("Hello, world!")
Hello, world!
Console comes from the .NET System namespace. The compiler also has an implicit System import by default; /noimplicitimports disables it.
Variables and constants
G# has var, let, and const declarations. var is mutable and may be declared with an explicit type and no initializer, which gives it the type's zero value. let is for values that are initialized once, including deconstruction forms. const is for compile-time constants.
package Tour.Basics
import System
var total = 0
let name = "G#"
const answer = 42
Console.WriteLine(name)
Console.WriteLine(answer)
Zero values are useful when a variable will be assigned later:
package GSharp.Example.ZeroValues
import System
var x int32
var flag bool
var text string
Console.WriteLine("x=${x} flag=${flag} text=[${text}]")
x = 42
flag = true
text = "set"
Console.WriteLine("x=${x} flag=${flag} text=[${text}]")
x=0 flag=False text=[]
x=42 flag=True text=[set]
Functions
Functions begin with func. Parameters are named, their types follow the names, and an optional return type follows the parameter list.
package GSharp.Example.Arithmetic
import System
func add(num1 int32, num2 int32) int32 {
return num1 + num2
}
var sum = 0
for i := 1 ... 5 {
sum = sum + i
}
Console.WriteLine(add(2, 3))
Console.WriteLine(sum)
5
10
Basic types
The primitive names are explicit about width: bool, int32, uint32, int64, uint64, float32, float64, decimal, char, string, and object are common examples. Older aliases such as int, uint, long, and byte are not G# built-in primitive names.
Strings support sigil-free interpolation with $name and braced ${expr} holes inside ordinary string literals. Holes may add an alignment and format clause, ${expr,alignment:format}:
package InterpolatedString
let name = "world"
let n = 6
Console.WriteLine("Hello, $name!")
Console.WriteLine("answer = ${n * 7}")
Console.WriteLine("$$ stays literal")
Hello, world!
answer = 42
$ stays literal
Next: Tour: Types and values.