Is there a way to rename keywords in c# for custom ones?

114 Views Asked by At

As a fun project and making some people laugh, I want to create a project that renames keywords such as true and false into something funnier in C#.

For example, replace True with Yass

How would I go about doing something like this? I saw stuff like that in JS, and I know you can do it in Python as well.

1

There are 1 best solutions below

0
Olivier Jacot-Descombes On

You can declare a constant: const bool Yass = true;


You can also prefix a keyword by @ to make it an identifier:

// Just for fun
const bool @true = false;
const bool @false = true;

But you will have to use the @ every time when using these constants. You cannot really change the built-in keywords in C# but contextual keywords can be used as valid identifiers outside of their context.

And since keywords and identifiers are case sensitive in C#, you can declare

const bool True = false;
const bool False = true;

You can also do fun stuff with Operator overloading - predefined unary, arithmetic, equality and comparison operators and let them do unexpected things.


A very surprising possibility is to let a class implement true and false operators - treat your objects as a Boolean value:

class Person
{
    public string Name { get; set; }

    public static bool operator true(Person p) => p.Name == "Yass";
    public static bool operator false(Person p) => p.Name != "Yass";
}

Now, persons are treated as Boolean values.

You can test it like this:

public static void Test()
{
    var p1 = new Person { Name = "Fizz" };
    var p2 = new Person { Name = "Yass" };

    if (p1) {
        Console.WriteLine("p1 is true");
    }
    if (p2) {
        Console.WriteLine("p2 is true");
    }
    Console.ReadKey();
}