Unable to identify some C# syntax for translation to VB.NET - c#

I'm translating some example code line by line from C# to VB.NET.
The lines which confuse me looks like this:
[Kernel(CustomFallbackMethod = "AddCpu")]
I see in the code that these lines appear just before the method declaration:
private static void
What kind of line appears before a method declaration? Or is it a continuation of the last? I hope this is obvious to a native C Sharper.

It's an Attribute. It's a way to mark up code that can be used at runtime or compile time.
I would google VB.NET and Attributes. You can read some passages here on O'Reilly
Your example would be converted to:
<Kernel(CustomFallbackMethod:="AddCpu")>
Be sure to use _ if you decide to put it on the line before your method.

Related

Howto create a const declaration using .NET Compiler Platform

I'm trying to create a small code generator using Roslyn or as it is called now .NET Compiler Platform, prevously I worked with codedom, which was cumbersome but MSDN got a reference, now Roslyn has little documentation and all documentation is focused on code analysis instead of code generation.
So my question is simple:
How can I create something like:
private const string MyString = "This is my string";
using the Compiler Platform classes? I've found something like FieldDeclarationSyntax and ExpressionSyntax, but all samples I've found generate things like
Myclass myvariable = new Myclass();
And there is nothing telling me something so simple as how to produce the
string type declaration.
any clue will be great.
Thank you in advance
You can use Roslyn Quoter to easily figure out how to build different pieces of syntax. In this case you're wanting to add the const and private modifiers to a field declaration so it would look something like:
var constField = SyntaxFactory.FieldDeclaration(
SyntaxFactory.VariableDeclaration(
SyntaxFactory.PredefinedType(
SyntaxFactory.Token(SyntaxKind.StringKeyword)))
.WithVariables(
SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(
SyntaxFactory.VariableDeclarator(
SyntaxFactory.Identifier("MyString"))
.WithInitializer(
SyntaxFactory.EqualsValueClause(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal("This is my string")))))))
.WithModifiers(
SyntaxFactory.TokenList(
new []{
SyntaxFactory.Token(SyntaxKind.PrivateKeyword),
SyntaxFactory.Token(SyntaxKind.ConstKeyword)}))))))

How do I create syntax nodes in Roslyn from scratch?

I would like to generate syntax nodes with the Roslyn API without having a pre-existing syntax node. That is, I cannot simply use the WithXYZ() methods on an existing object to modify it because there is no existing object.
For example, I would like to generate an InvocationExpressionSyntax object. Assuming a constructor was available, I could do something like
var invoke = new InvocationExpressionSyntax(expression, arguments);
But the constructor for InvocationExpressionSyntax seems to not be public.
http://www.philjhale.com/2012/10/getting-started-with-roslyn.html
this blog suggests that I can use an API such as
Syntax.InvocationExpression()
but I don't see what Syntax refers to, and I don't see anything that resembles it in the Roslyn API.
I did find Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory that lets me do
var invoke = SyntaxFactory.InvocationExpression().WithExpression(expression);
And this works well enough for me. There is also Microsoft.CodeAnalysis.CSharp.SyntaxFactory for anyone wondering.
Is SyntaxFactory the proper way to create new syntax nodes?
The way I found SyntaxFactory.InvocationExpression was by looking at the PublicAPI.txt file in the roslyn source code (https://github.com/dotnet/roslyn) under the src/Compilers/VisualBasic/Portable directory. Otherwise, I don't see where SyntaxFactory is documented.
As the other answer stated, the SyntaxFactory is the correct class to use. As you have found there are two syntax factories available, Microsoft.CodeAnalysis.CSharp.SyntaxFactory and Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory, depending on which language you are using.
Usually the calls into the SyntaxFactory are chained together, so you end up with many calls to the SytnaxFactory methods to generate even simple lines of code. For example, the code Console.WriteLine("A"); would be represented by the following calls to the Syntax Factory:
var console = SyntaxFactory.IdentifierName("Console");
var writeline = SyntaxFactory.IdentifierName("WriteLine");
var memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, console, writeline);
var argument = SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("A")));
var argumentList = SyntaxFactory.SeparatedList(new[] { argument });
var writeLineCall =
SyntaxFactory.ExpressionStatement(
SyntaxFactory.InvocationExpression(memberaccess,
SyntaxFactory.ArgumentList(argumentList)));
If you are unsure of how to generate nodes for some specific code, Kirill Osenkov created the Roslyn Quoter project on GitHub, which you can use to generate the SyntaxFactory code for you.
I recently did a blog post on this topic if you would like to read further.
Yes, the SyntaxFactory type is the way to create syntax nodes from scratch.

How do I convert this VB.NET array expression to C#

In VB.net, I can write:
If {"red", "blue"}.Contains("blue") Then Return True
and the Contains seems to be from Linq.Enumerable(Of T).
I'm having trouble converting it to C# - when I use an online conversion tool like the one from Developer Fusion, it gives me:
if ({"red", "blue"}.Contains("blue")) return true;
but it doesn't compile, saying it's unable to resolve the symbol Contains which isn't very helpful. I'm sure it's a simple syntax issue, but I'm not sure what you call an example like this.
I don't need to instantiate the array, since I'm just using it to evaluate the expression inline. This seems to be possible in VB.NET. What do you call this - a static array? constant array? anonymous array? some combination of those listed?
I'd like to know how to write this in C#, and also what this is called (I'll update the question title and tags to better reflect what I'm asking when someone can answer that). Thanks!
This would be your direct conversion
if (new []{"red", "blue"}.Contains("blue")) return true;
Oh, it's called an array initializer

Changing Variable Type on RunTime

Today i had a challenge with my College and i gaved up ,no idea how to achieve it .
Is there a way to declare a String ,as Constant and on Load Event maybe using Reflection to change String to non-Constant assign a value from XML ,than Change it to Constant again .
And all of the Code which does that (Constant to Non-Constant),should be Stored in a String ,and on Load before Type Change ,it should be Decrypted and Injected into the Application .
example:
private const String RegNumber = "";
//Change RegNumber to Writable String
//Change RegNumber value
//Than Change RegNumber back to const again
PS : Please sorry but i have no idea where to start ,and show here some code .
You can't declare it as const but you can declare it as static readonly:
private static readonly string Foo = ReadValueFromAssembly();
static string ReadValueFromAssembly()
{
// Perform your logic and return the string here
}
Would that do everything you need? It's not really clear what you mean about the "code which does that [...] should be decrypted and injected into the application" but you can make the above method do anything you need it to as normal.
As a side-note, it's generally a bad idea to do a lot of work in a type initializer like this.
EDIT: You can store code as a string, use CSharpCodeProvider to compile it at execution time, and then execute the compiled code. I have a sample of this in "Snippy" which I used for C# in Depth as a quick tool for compiling snippets.
It may not even exist at runtime, the compiler could have just replaced all usages of it with their literal values (in fact, it probably has, though I don't think it's required to by the standard).
So no, I don't see how this could be possible.
It is theoratically possible. See
How to programmatically compile code using C# compiler
http://support.microsoft.com/kb/304655
You can write the code in a string and compile using the API mentioned in above article.
I have not done that before but it should give you an idea on how to start.
Also see,
Can I change value of constant in C#?

C# version of __FUNCTION__ macro

Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.
Try using this instead.
System.Reflection.MethodBase.GetCurrentMethod().Name
C# doesn't have __LINE__ or __FUNCTION__ macros like C++ but there are equivalents
What I currently use is a function like this:
using System.Diagnostics;
public string __Function() {
StackTrace stackTrace = new StackTrace();
return stackTrace.GetFrame(1).GetMethod().Name;
}
When I need __FUNCTION__, I just call the __Function() instead. For example:
Debug.Assert(false, __Function() + ": Unhandled option");
Of course this solution uses reflection too, but it is the best option I can find. Since I only use it for Debugging (not Tracing in release builds) the performance hit is not important.
I guess what I should do is create debug functions and tag them with
[ Conditional("Debug") ]
instead, but I haven't got around to that.
Thanks to Jeff Mastry for his solution to this.
Unfortunately there is no equivalent version of that macro in C#. I don't consider the GetCurrentMethodName() solution equivalent to the C++ __FUNCTION__ macro. Namely becase the C++ version is a compile time computation of the name. For C# this is a runtime calculation and incurs a performance hit.
I'm not making any assumtions about the severity of the cost but there is one
The following should work, although it will be evaluated at runtime instead of during compilation.
System.Reflection.MethodBase.GetCurrentMethod().Name
I use this:
public static string CallerName([CallerMemberName] string callerName = "")
{
return callerName;
}
Usage example:
s_log.DebugFormat("{0}", CallerName());
The down side of using it is that every time you want to print the caller name, you need to jump to the function ==> time consuming & performance hit!
So, I use it for debugging perpose and if I need to print also in production code, I usually inline the function name into the log.Debug, e.g. :
s_log.Debug("CallerName");
HTH..
This is added in .NET 4.5.
See #roken's answer here:
Do __LINE__ __FILE__ equivalents exist in C#?

Categories