Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to do inline function in vb.net?

Tags:

.net

vb.net

the question is in the title

like image 998
Fredou Avatar asked Jan 10 '09 21:01

Fredou


2 Answers

The answers I've seen assume you're talking about compile or JIT-time inlining - and they're entirely correct. However, the other use of the word "inline" that I've heard is for things like lambda expressions - in C#, things like:

public IEnumerable<int> Foo()
{
    int[] numbers = new[] { 1, 5, 2, 5, 6 };

    return numbers.Select(x => x+10);
}

The x => x+10 (a lambda expression) can be regarded as an "inline function" in source code terms, in that it's an extra function declared "inline" in another method.

And yes, VB9 has this:

Dim len As Func(Of String, Integer) = Function(x) x.Length       
Console.WriteLine(len("foo"))

I believe there are more restrictions in VB9 compared with C# though - for instance, I don't think you can create an Action<T> (or any other delegate type with a void return type) using a lambda expression in VB9, whereas it's easy in C#. Likewise I believe the lambda has to be just a single expression in VB9, whereas in C# it can be a whole block in braces.

As of VB10, you can create multi-line lambda expressions in VB too.

Of course, if the question was really referring to the execution rather than the source code, all of this is irrelevant :)

like image 113
Jon Skeet Avatar answered Oct 07 '22 17:10

Jon Skeet


Inlining is the responsibility of the CLR (JIT) and there are some conditions as to when a function is inlined:

  1. The code size is smaller than 32 bytes of IL.
  2. The function does not contain "complex" constructs, e.g. loops, switch etc.
  3. The function does not contain try/catch/finally.
  4. The function is not declared as virtual.

As you will probably find out, 32 bytes is not very much in terms of code, it is suitable for quick and small if-else condition testing, property getters/setters. I don't think you can gain any speed from inlining a bigger amount of code.

like image 30
liggett78 Avatar answered Oct 07 '22 17:10

liggett78