CodeDom method body definition - c#

I would like to understand which is the cleanest way to generate class with Code Dom, in particular i am interestd in method body generation.
I have see MSDN example (first between google's results), but method body generation seems to me a little complicatied and it only consists in few simple instructions (i would like to write some lambda instead).

CodedDom allows you to write any code you wish for with CodeSnippetStatement. you can check the code example in the link.
not everything is supported in CodeDom , but if your purpose is to create code on run time, you should read about Expressions.
P.S: microsoft no longer support CodeDom

Related

How to see boilerplate code for top-level statements in C#?

I'm going through this C# intro tutorial by MS, and in the section "Fix the "format" error" I'm supposed to delete code in the namespace, but I'm not seeing that namespace since I'm in the "top-level statements" mode. How do I reveal the boilerplate code that is underneath?
As described by Top-level statements - programs without Main methods:
Starting in C# 9, you don't have to explicitly include a Main method in a console application project. Instead, you can use the top-level statements feature to minimize the code you have to write. In this case, the compiler generates a class and Main method entry point for the application.
Here's a Program.cs file that is a complete C# program in C# 10:
Console.WriteLine("Hello World!");
Top-level statements let you write simple programs for small utilities such as Azure Functions and GitHub Actions. They also make it simpler for new C# programmers to get started learning and writing code.
This means that the Top-Level statements is a feature of a comiler, not of the editor. The Main method and the class (things you call "boilerplate") are not present in the source code - they are generated by the compiler.
Adding to the above answer is its Compiler feature.
The compiler generates a method to serve as the program entry point
for a project with top-level statements. The name of this method isn't
actually Main, it's an implementation detail that your code can't
reference directly. The signature of the method depends on whether the
top-level statements contain the await keyword or the return
statement.
The following table shows what the method signature would look like, using the method name Main in the table for convenience.
Reference:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements#implicit-entry-point-method
Whoever updated the tutorial to .NET 6 with top-level statements (see the commit) forgot to update the part in question. To see the full previous version of the code you can switch tutorial to VS 2019 version either by using dropdown at the top of table of contents:
Or just by following this link.
The previous version also should work, you should be able to replace the contents of your Program.cs file with code from this section and proceed with tutorial from here.

Is this possible in C# to ensure compile time that method/class have given signature

Is this possible in C# to ensure that method/class have given signature.
For example I want to ensure that some method is public and static.
When isn't I want to this method red underlined.
I need it because I'm using this with component test runner app which uses reflection and expects public static bool methods from dlls. I want to force programmers to write public static bools component test methods. Is this a possibility to force them compile time? Or maybe force them build time by adding another simple app that checks it by reflection during post build event?
Is this possible? Maybe by method attributes? By reflection? But how?
Unfortunately, you cannot change/extend the C# compiler to achieve what you want here. However, there is a Microsoft project called Roslyn which exposes a public API for implementing your own extensions to the C# compiling pipeline.
Using Roslyn's structures, it should be easy to traverse your source code syntax trees looking for methods that are not public/static. Once you find them, you could generate a code issue reporting the problem; those issues are shown both in the code editor (wavy underline) and in the Errors List panel. From Roslyn's official documentation:
The code issue provider makes it easy to surface an error or suggestion to the user as a wavy underline in the editor or appear in the Error List window.
Look around for examples of CodeIssueProviders; it could be useful for what you need to do.

Generate C# assembly from source code text file

I have a C# source code in the file (or in text string). How can I use reflection emit to generate and execute this code?
There are so many examples where people generate one class, then add a method etc, but I need top compile-on-the-fly huge piece of C# code, couple kilobytes.
Reflection.Emit is for working with code at the IL level, it knows nothing about how to compile C# source code, so you can't use it for that.
What you can use for this instead is CodeDOM, specifically the CSharpCodeProvider class and its CompileAssemblyFromFile () or CompileAssemblyFromSource() methods.

Generate dynamic code from string with Reflection.Emit

I have stored some C# code in a database table.
I have the whole code of a base class in a string.
With the stored C# code in hand, I add to the class a method named m1 that contains a return <<some C# code>>; (the method always returns object so the C# code can be: 88 + 90, "hello world", this.ToString(), etc.), save it to a file and compile it with CSharpCodeProvider, and run it on my program.
The stored C# code can use some methods in the base class.
This scheme works very well.
Now, I would to use Reflection.Emit to do this, to avoid the compiling step.
Is this possible, and if so, how would it be done?
Now, I would to use Reflection.Emit to do this, to avoid the compiling step.
That doesn't make much sense to me. If you have source code that you want to execute, you basically have two options:
Compile it to some other form that can then be directly executed. (Classic compiled languages like C work like this.)
Parse it into some in-memory structure and then execute that, piece by piece. (Classic interpreted languages work like this, like JavaScript in older browsers.)
Things aren't actually as simple as that these days, because of virtual machines and intermediate languages etc., but those are the basic choices.
If you don't want to use CodeDOM, that leaves you two choices (corresponding to the two options above):
Parse the code and then create some executable form from it, possibly using Reflection.Emit.
Parse the code and directly execute the result. You don't need Reflection.Emit for that.
Choice 1 means you would need to implement full C# compiler. Choice 2 means you would need to implement a half of C# compiler, plus an interpreter of your in-memory structure. In both cases, it would be a giant project and you wouldn't really “avoid the compiling step”.

Refactoring duplicate code into methods

I am using Resharper for refactoring. What is this type of feature called when you have the same code in around 5 different events being called but you want to replace them with a method call? And place that code in that method.
All done automatically.
Thanks
I've been working on a Resharper plugin that does what you are asking. That is, it scans your code, searching for sections that can be replaced by an existing method call. A section can be a whole method or just a part of a method. When it finds one, the lightbulb pops up and offers to replace said section with a call to the existing method.
(source: landofjosh.com)
I call it AgentRalph. At this point it's not ready for production use, but I've been making a lot of progress and hope to make a release soon.
Extract Method.
See our C# CloneDR. While it doesn't replace redundant code with function calls, it does tell you where they are across very large system, and forms the essential abstraction (procedure body and parameters). The web link has example clone analyses for the C# equivalent of Hibernate (NHibernate).

Categories

Resources