Skip to content

Native Functions

EverSharp provides over 100 built-in native functions for common operations. Functions are organized into categories based on their purpose.


Function Categories

Category Count Description
Mathematics 7 Arithmetic and mathematical operations
Date & Time 26 Date/time creation, manipulation, calculations, and timezones
Strings 14 String manipulation and text operations
Arrays 29 Array creation, transformation, and manipulation
Conversions 8 Type conversion functions
Lookups 6 Array filtering by comparison
Options 3 Parsing Name##Value##InfoText option strings
Testing 3 Assertions for tests and runtime validation
Utilities 11 Logging, dynamic access, and helper functions

Mathematics

Arithmetic and mathematical operations.

Function Description
$Max(a, b) Returns the larger of two numbers
$Min(a, b) Returns the smaller of two numbers
$Abs(value) Returns the absolute value
$Round(value, decimals) Rounds to specified decimal places
$Pow(base, exponent) Raises a number to a power
$Ln(value) Returns the natural logarithm
$Sum(array, property?) Sums array values, or a property of each object

Example:

max = $Max(10, 20); // 20
min = $Min(10, 20); // 10
abs = $Abs(-15); // 15
rounded = $Round(3.14159, 2); // 3.14
power = $Pow(2, 3); // 8
ln = $Ln(2.718281828); // about 1
sum = $Sum([1, 2, 3, 4, 5]); // 15

→ See all mathematics functions


Date & Time

Date and time creation, manipulation, calculations, and timezone conversion.

Function Description
$Now() Current UTC date and time
$Today() Current date (midnight)
$ToDate(value) Parse value to DateTime
.ToDateUTC(tz?) Convert to UTC, optionally from a timezone
.ToDateOnly() Convert to DateOnly
.ToDateLocalTime(tz) Convert UTC value to timezone local time
.ToShortDateString() Format value as short date
.GetTimeZoneAbbreviation(tz) Get timezone abbreviation for the date
$ConvertTimeFromUtc(date, tz) Convert UTC date to timezone time
$ConvertTimeToUtc(date, tz) Convert timezone time to UTC
$AddSeconds(date, n) Add seconds to date
$AddMinutes(date, n) Add minutes to date
$AddHours(date, n) Add hours to date
$AddDays(date, n) Add days to date
$AddMonths(date, n) Add months to date
$AddYears(date, n) Add years to date
$DifferenceInSeconds(date1, date2) Seconds between dates
$DifferenceInMinutes(date1, date2) Minutes between dates
$DifferenceInHours(date1, date2) Hours between dates
$DifferenceInDays(date1, date2) Days between dates
$DifferenceInYears(date1, date2) Whole years between dates
$Year(date) Extract year component
$Month(date) Extract month component
$Day(date) Extract day component
$StartOfDay(date) Date at 00:00:00
$EndOfDay(date) Date at 23:59:59.999

tz accepts an IANA or Windows timezone ID. All except $ConvertTimeFromUtc also accept a 2-letter ISO country code (e.g. "ES").

Example:

now = $Now();
today = $Today();
futureDate = $AddDays(today, 30);
daysDiff = $DifferenceInDays(futureDate, today); // 30
year = $Year(now);
utc = $ConvertTimeToUtc("2025-08-13 10:00", "Europe/Madrid");

→ See all date/time functions


Strings

String manipulation and text operations. Most are instance methods.

Function Description
.ToUpper() Convert to uppercase
.ToLower() Convert to lowercase
.Trim() Remove leading/trailing whitespace
.Split(separator) Split into array
.Substring(start) Extract from index to end
.Substring(start, len) Extract substring of length
.Contains(substring) Check if contains substring
.StartsWith(prefix) Check if starts with prefix
.EndsWith(suffix) Check if ends with suffix
.Replace(old, new) Replace occurrences
.RemoveNonAlpha() Remove non-alphanumeric characters
.GetCountryNameFromISOCode() Convert ISO code to country name
.ToStringSafe() Safe string conversion
$Length(value) Length of a string or array

Example:

text = "  Hello World  ";
upper = text.ToUpper(); // "  HELLO WORLD  "
trimmed = text.Trim(); // "Hello World"
parts = trimmed.Split(" "); // ["Hello", "World"]
sub = trimmed.Substring(0, 5); // "Hello"
hasHello = text.Contains("Hello"); // true

→ See all string functions


Arrays

Array creation, transformation, filtering, and manipulation.

Function Description
$Array(...) Create array from values
$AddToArray(array, value) Add value and return the array
$Sort(array, property?) Sort ascending, optionally by property
$Reverse(array) Reverse order
$Map(array, property) Extract a property from each object
$Length(array) Number of elements
.Filter(predicate) / .Where Filter elements
.Map(transform) / .Select Transform elements
.ReduceToNum(fn) Reduce to number (starts at 0)
.ReduceToStr(fn) Reduce to string (starts at "")
.ReduceToObj(fn) Reduce to object (starts at {})
.Find(predicate) Find first match
.Any(predicate) Check if any match
.IndexOf(value) Index of value
.ForEach(action) Run action for each element
.OrderBy(selector) Sort ascending
.OrderByDescending(selector) Sort descending
.Take(count) First n elements
.Slice(start, end?) Sub-array
.Distinct() Remove duplicates
.Reverse() Reverse order
.Join(separator) Join into string
.Push(value) / .Add Add element to end
.AddRange(array) Append all elements
.Insert(index, value) Insert at index
.Remove(value) Remove value
.RemoveAt(index) Remove at index
.Clear() Remove all elements
.Length Number of elements

Example:

numbers = [1, 2, 3, 4, 5];
evens = numbers.Filter((x) => x % 2 == 0); // [2, 4]
doubled = numbers.Map((x) => x * 2); // [2, 4, 6, 8, 10]
sum = numbers.ReduceToNum((acc, x) => acc + x); // 15
sorted = numbers.OrderByDescending((x) => x); // [5, 4, 3, 2, 1]

→ See all array functions


Conversions

Type conversion functions. Apart from $ToDate, these are instance methods.

Function Description
$ToDate(value) Convert to DateTime
.ToNumber() Convert to decimal
.ToString(format?) Convert to string, optionally formatted
.ToStringSafe() Safe null-tolerant string
.ToDateUTC(tz?) Convert value to UTC DateTime
.ToDateOnly() Convert to DateOnly
.ToArray() JSON string to array
.ToDictionary() JSON string to object

Example:

text = "100";
num = text.ToNumber(); // 100
str = num.ToString("N2"); // "100.00"
date = $ToDate("2024-01-15");
dateOnly = date.ToDateOnly();

→ See all conversion functions


Lookups

Filter arrays by comparing each element, or a property of each element, against a value.

Function Description
$FindEquals(array, property?, value) Elements equal to value
$FindNotEquals(array, property?, value) Elements not equal to value
$FindGreaterThan(array, property?, value) Elements greater than value
$FindGreaterThanOrEqual(array, property?, value) Elements greater than or equal to value
$FindLessThan(array, property?, value) Elements less than value
$FindLessThanOrEqual(array, property?, value) Elements less than or equal to value

Example:

adults = $FindGreaterThanOrEqual(people, "Age", 18);
singles = $FindEquals(policies, "PolicyType", "Single");

→ See all lookup functions


Options

Parse option strings in the "Name##Value##InfoText" format.

Function Description
.GetOptionName() Name (first) part
.GetOptionValue() Value (second) part
.GetOptionInfoText() Info text (third) part

Example:

option = "Gold Plan##GOLD##Includes roadside assistance";
name = option.GetOptionName(); // "Gold Plan"
value = option.GetOptionValue(); // "GOLD"

→ See all option functions


Testing

Assertions for tests and runtime validation.

Function Description
$AssertTrue(condition) Fail unless condition is true
$AssertFalse(condition) Fail unless condition is false
$AssertAreEqual(expected, actual) Fail unless values are equal

Example:

$AssertAreEqual(15, $Sum([1, 2, 3, 4, 5]));
$AssertTrue($IsNumber("42"));

→ See all testing functions


Utilities

Logging, dynamic property access, and helper functions.

Function Description
$Log(message, args...) Log to output
$GetValue(obj, prop) Get property by name
$HasProperty(obj, prop) Check whether a property exists
$SetValue(obj, prop, val) Set property by name
$IsInRange(min, max, val) Check if value in range
$IsNumber(value) Check if a value can be treated as number
$Fetch(url, options?) HTTP request
$Stringify(value) Serialize to JSON
.AddProperty(name, value) Return a new object with extra property
.HasProperty(name) Check whether an object has a property (returns false on null/non-object)
.IsNullOrEmpty() Check if null, empty string, array, or object

Example:

$Log("Hello World");
obj = { "name": "Alice" };
value = $GetValue(obj, "name"); // "Alice"
exists = obj.HasProperty("name"); // true
isNumeric = $IsNumber("42.5"); // true
$SetValue(obj, "age", 30);
inRange = $IsInRange(1, 10, 5); // true
json = $Stringify(obj);

→ See all utility functions


Function Naming Conventions

$ Prefix Functions

Functions with $ prefix are standalone/global functions:

$Max(10, 20);
$Now();
$ToDate("2024-01-15");
$Log("message");

Instance Methods

Methods called on values (no $ prefix):

// String methods
text.ToUpper();
text.Split(",");

// Array methods
array.Filter((x) => x > 0);
array.Map((x) => x * 2);

// Number methods
number.ToString();

Parameter Patterns

Fixed Arity

Most functions have fixed parameter counts:

$Max(a, b); // Always 2 parameters
$Round(value, decimals); // Always 2 parameters
$AddDays(date, days); // Always 2 parameters

Variable Arity

Some functions accept variable parameters:

$Log(message); // 1+ parameters
$Log("Value: {0}", value); // Format string + args
$Array(1, 2, 3, 4, 5); // 0+ parameters

Lambda Parameters

Array methods that take lambdas:

// 1 parameter: element
array.Filter((x) => x > 0);
array.Find((x) => x == target);

// 2 parameters: element, index
array.Map((x, i) => x + i);
array.ForEach((x, i) => $Log(i + ": " + x));

// 2 parameters: accumulator, element
array.ReduceToNum((acc, x) => acc + x);

Common Usage Patterns

Pattern 1: Chaining Array Operations

result = data
  .Filter((x) => x.isActive)
  .Map((x) => x.value)
  .OrderByDescending((x) => x)
  .Take(10);

Pattern 2: Date Calculations

today = $Today();
futureDate = $AddDays(today, 30);
age = $DifferenceInYears($Today(), birthDate);

Pattern 3: String Processing

text = "  hello world  ";
processed = text.Trim().ToUpper().Replace("WORLD", "EVERSHARP");

Pattern 4: Dynamic Object Access

propertyName = "premium";
value = $GetValue(policy, propertyName);
$SetValue(policy, "discount", 0.15);

Pattern 5: Validation

isValid = $IsInRange(18, 100, age) && email.Contains("@") && name.Trim() != "";

Error Handling

Functions may throw runtime exceptions:

// Type mismatch
// $Max("text", 10)                     // ERROR: Not a number

// Null value
// nullValue.ToUpper()                  // ERROR: Null reference

// Invalid format
// $ToDate("not a date")                // ERROR: Parse failed

Safe patterns:

// Check for null
if (value != null) {
  upper = value.ToUpper();
}

// Validate before conversion
if (text != null && text != "") {
  number = text.ToNumber();
}

// Check array length
if (items.Length > 0) {
  first = items[0];
}

Performance Considerations

Prefer Native Functions

// Less efficient: Manual loop
sum = 0;
i = 0;
while (i < numbers.Length) {
  sum += numbers[i];
  i++;
}

// More efficient: Native function
sum = $Sum(numbers);

Chain Operations

// Less efficient: Multiple intermediate arrays
filtered = data.Filter((x) => x.isActive);
mapped = filtered.Map((x) => x.value);
sorted = mapped.OrderBy((x) => x);

// More efficient: Single chain
result = data
  .Filter((x) => x.isActive)
  .Map((x) => x.value)
  .OrderBy((x) => x);

Next Steps