Question

I know this is wrong (trying to code in C# with a C/C++ mindset). But is it possible to create inline functions / inline recursive functions (til the Nth call) / macros in C#?

Because if I intend to call the same function 1000 times, but it's a simple function, the overhead of creating the stack is quite big... And unnecessary.

In C i could use inline functions. Is there something like that in C#?

Again... I'm not saying that C/C++ is better... I'm just new to C# and have none to ask those simple questions...

Was it helpful?

Solution

Inline functions in C#?

Finally in .NET 4.5, the CLR allows one to force1 method inlining using MethodImplOptions.AggressiveInlining value. It is also available in the Mono's trunk (committed today).

[MethodImplAttribute(MethodImplOptions.AggressiveInlining)] 
void Func()
{
    Console.WriteLine("Hello Inline");
}

OTHER TIPS

The answer should be: don't worry about it. No need to start with micro-optimizations unless you've tested it and it's actually a problem. 1000 function calls is nothing until it's something. This is majorly overshadowed by a single network call. Write your program. Check the performance against the goals. If it's not performant enough, use a profiler and figure out where your problem spots are.

Yes, C# is a very powerful general purpose language that can do nearly anything. While, inline functions / macros are generally frowned upon, C# does provide you with multiple tools that can accomplish this in a more concise and precise fashion. For example, you may consider using template files which can be used (and reused) in nearly all forms of .NET applications (web, desktop, console, etc).

http://msdn.microsoft.com/en-us/data/gg558520.aspx

From the article:

What Can T4 Templates Do For Me?

By combining literal text, imperative code, and processing directives, you can transform data in your environment into buildable artifacts for your project. For example, inside a template you might write some C# or Visual Basic code to call a web service or open an Excel spreadsheet. You can use the information you retrieve from those data sources to generate code for business rules, data validation logic, or data transfer objects. The generated code is available when you compile your application.

If you're new to programming I would recommend against implementing templates. They are not easy to debug in an N-Tier application because they get generated and ran at run-time. However, it is an interesting read and opens up many possibilities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top