Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Voldemort types in C#

Tags:

closures

c#

d

As you probably know in D language we have an ability called Voldemort Types and they are used as internal types that implement particular range function:

auto createVoldemortType(int value)
{
    struct TheUnnameable
    {
        int getValue() { return value; }
    }
    return TheUnnameable();
}

Here is how the Voldemort type can be used:

auto voldemort = createVoldemortType(123);
writeln(voldemort.getValue());  // prints 123

Now I want to make sure that, Is this the equivalent to delegate in C#?

public static void Main()
{
    var voldemort = createVoldemortType(123);
    Console.WriteLine(voldemort());

}
public static Func<int> createVoldemortType(int value)
{
    Func<int> theUnnameable = delegate()
                              {
                                    return value;
                              };
    return theUnnameable;
} 
like image 485
Sirwan Afifi Avatar asked Sep 11 '16 06:09

Sirwan Afifi


1 Answers

There isn't an exact equivalent of a Voldermort type in C#. The closest you have to such local scope classes is called Anonymous Types. Problem is, unlike Voldermort types, you can't refer to their static type at compile time outside of the local declaration:

public object SomeLocalMethod() // Must return either `dynamic` over `object`
{
    var myAnonClass = new { X = 1, Y = "Hello" };
    Console.WriteLine(myAnonClass.Y); // Prints "Hello";
    return myAnonClass;
}

void Main()
{
    object tryLookAtAnon = SomeLocalMethod(); // No access to "X" or "Y" variables here.
}

If however, we enter the land of dynamic, you can refer to the underlying class fields, but we lose type safety:

void Main()
{
    dynamic tryLookAtAnon = SomeLocalMethod();
    Console.WriteLine(tryLookAtAnon.X); // prints 1
}

public dynamic SomeLocalMethod() 
{
    var myAnonClass = new { X = 1, Y = "Hello" };
    Console.WriteLine(myAnonClass.Y); // Prints "Hello";
    return myAnonClass;
}

A delegate in C# is similar to a delegate in D. They hold a reference to a function.

like image 150
Yuval Itzchakov Avatar answered Sep 28 '22 06:09

Yuval Itzchakov