-
Notifications
You must be signed in to change notification settings - Fork 3
Literal rendering
The TryRenderLiteral and RenderLiteral functions take an object/value and a language, and return a string with a language-specific literal for that object. For example:
// using static ZSpitz.Util.Functions
Console.WriteLine(RenderLiteral(true, "C#"));
// prints: true
Console.WriteLine(RenderLiteral(true, "Visual Basic"));
// prints: TrueLiterals are rendered as follows, depending on the value passed into the language parameter:
| Type / value | "C#" |
"Visual Basic" |
Anything else |
|---|---|---|---|
null |
null |
Nothing |
␀ |
| numeric types | ToString | ToString | ToString |
| System.Boolean |
true / false
|
True / False
|
ToString |
| System.Char | 'a' |
"a"C |
|
| System.DateTime |
#1-1-1980# (using ToString) |
||
| System.String (no control characters) | "abcd" |
"abcd" |
"abcd" |
| System.String (with control characters) | "ab\ncd" |
"abcd"
|
|
| Enum values | DayOfWeek.Tuesday |
DayOfWeek.Tuesday |
DayOfWeek.Tuesday |
| Flag enum values | BindingFlags.Static | BindingFlags.Public |
BindingFlags.Static Or BindingFlags.Public |
BindingFlags.Static, BindingFlags.Public |
| 1-dimensional array | new object[] { 1, "2" } |
{ 1, "2" } |
|
| System.Tuple, System.ValueTuple | (1, "2") |
(1, "2") |
(1, "2") |
If the object/value doesn't have a matching rendering it will display as #<TypeName> -- e.g. #String, #ArrayList or #Random.
Some instances of types in the System.Reflection namespace have special handling, using the language-specific type operator and reflection methods. For example, a MethodInfo will be rendered as a call to GetMethod; a PropertyInfo, as a call to GetProperty.
| Type / value | "C#" |
"Visual Basic" |
|---|---|---|
| Type | typeof(string) |
GetType(String) |
| ByRef type | typeof(string).MakeByRef() |
GetType(String).MakeByRef() |
| ConstructorInfo | typeof(Timer).GetConstructor(new Type[] { }) |
GetType(Timer).GetConstructor({ }) |
| EventInfo | typeof(Timer).GetEvent("Elapsed") |
GetType(String).GetEvent("Elapsed") |
| FieldInfo | typeof(string).GetField("m_stringLength") |
GetType(String).GetField("m_stringLength") |
| MethodInfo | typeof(string).GetMethod("Clone") |
GetType(String).GetMethod("Clone") |
| PropertyInfo | typeof(string).GetProperty("Length") |
GetType(String).GetProperty("Length") |
If the relevant reflection method requires additional parameters in order to resolve the member -- e.g. multiple methods with the same name, or a non-public or static property -- those parameters will also be rendered:
var writeLine = typeof(Console).GetMethod("WriteLine", new Type[] { });
Console.WriteLine(RenderLiteral(writeLine));
// prints: typeof(Console).GetMethod("WriteLine", new Type[] { })