0

I'm working on a C# project, I want to use an anonymous Method Or Function that returns a value to a variable.

I tried this :

    byte[] V;
    V= new byte[]()
    {
        //Some code here
        return new byte[]{0,1,2,3};
        
    }

But I got errors

How can I use anonymous Method Or Function to returns a value to V variable ?

I want just to knw how can I use anonymous method tat returns a value to a variable.

2
  • 2
    why do you want an anonymous method that you execite immediately? Why even anonymous? Even there´s some logic that can be extracted to a method that has a name describing what it´s supposed to do, or there´s nothing to be extracted at all. There are local functions, however Commented Nov 9, 2020 at 7:34
  • Please explain the rationale behind wanting to use a function for this, in place of just having the code directly placed in your main code path. In the code in your question there is absolutely no need for a function at all, and knowing why you want to do this might indicate better approaches. Commented Nov 9, 2020 at 8:16

1 Answer 1

2

There are a couple of opportunities, all having their own advantages and disadvantages.

  1. a delegate

    byte[] V;
    V= new Func<byte[]>(() => ()
    {
        //Some code here
        return new byte[]{0,1,2,3};    
    }();
    
  2. a local function

    void DoSomething()
    {
        byte[] V;
    
        byte[]MyLocalFunction()
        {
            //Some code here
            return new byte[]{0,1,2,3};
        }
        V = MyLocalFunction();
    }
    
  3. a normal private method with a name

Personally I prefer 3 the most, as you have a name that clearly describes what the method should do. 2 also has a name and in fact compiles to a private static method within your class, so it may seem appropriate as well. 1 just makes your code har to understand and read. There are use-caes for that, but in most cases I won´t suggest to use it.

So if you think there is some logic within a member that should be extracted in some way, you give it a name. This way you can easily extract that to another class later on, if you need to.

Sign up to request clarification or add additional context in comments.

2 Comments

If you are on .net core and the data is supposed to be readonly, a ReadOnlySpan<Byte> is far better in terms of performance since that will end up being written to static data section of the binary.
Massive thanks #HimBromBeere, this is a very beneficial answer, I really appreciate this for you, again let me say massive thanks sir and please accept all my respect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.