0

Is there a way to shorten the following:

public class Test
{
    /* declares a delegate type (named MyDelegateType) which has a single parameter of 
        type float and doesn't return anything. */
    public delegate void MyDelegateType(float f); 

    /* defines a reference to an object of type MyDelegateType */                                                
    private MyDelegateType MyDelegateRef;

    ... // say we have a Property to set and get MyDelegateRef, and a method
        // for executing its target
}

into one line, without using Action/Func types?

I'm asking this to understand if there's an equivalent to what we can do in C++ (or C) with a function pointer:

class Test
{
   /* defines a pointer (named MyFP) to a function with a single 
      parameter of type float, and doesn't return anything */
   void(*MyFP)(float); 

   ... // say we have a Setter & Getter functions, and an Execute 
       // function for executing MyFP
}
OfirD
  • 4,693
  • 2
  • 22
  • 52
  • Why don't you want a 'Func'? As far as I understand with very limited C++ knowledge a function pointer also is some kind of a 'Func' type. – Bill Tür Sep 04 '16 at 11:28
  • Why without those type that do just what you want? – Stefan Sep 04 '16 at 11:39
  • @ThomasSchremser, a function pointer can function either as `Action` or `Func` type. It's not that I don't want a `Action`/`Func`, this question is purely asked to understand the syntactic possibilities. – OfirD Sep 04 '16 at 11:40
  • 1
    The C# language in general does not permit declaring a type in the same statement as declaring an object of that type. Works in C++ but a never-ending source of very hard to diagnose compiler errors, particularly so if the declaration is in a header file and is missing a semi-colon after the closing brace. Everybody forgets. The C# team was made up from very experienced programmers that knew C++ well, including all its traps. And aimed to avoid them. Using the Func<> type works because that one is of course already declared. You'll get used to it easily. – Hans Passant Sep 04 '16 at 12:31
  • Just adding this for a related reference: Eric Lippert's [post](http://stackoverflow.com/a/36560177/6474510) about (not) supporting function pointers in C# – OfirD Sep 05 '16 at 20:49

1 Answers1

1

No, that's why Action<T> and Func<T> were included in the framework.

Florian Greinacher
  • 13,628
  • 1
  • 31
  • 50