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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With