Can we use Delegates in Getters

Viewed 76

We know that, it is possible to use Lambda functions as getters like,

private string _name;
public string Name
{
    get => _name;
}

But, can we make use of anonymous functions with delegates as getters like,

private string _name;
public string Name
{
    get => delegate { return _name; };
}

It's getting compilation errors.

1 Answers

Delegate are nothing but a pointer to a method (overly simplified, however you can find the detailed information here Using Delegates). So the answer is yes.

You can use delegates, actions, funcs etc.

I give you the world's most contrived example:

private static string _name = "bob";

public delegate string Del(string message);

public static string DoSomething(string message) => message + "1";

private static readonly Del Handler = DoSomething;

public string Name
{
    get => Handler(_name);
}
Related