C# Alias an Attribute (such as Inline Hinting) - c#

I've been wanting for a while to shorten the (no-using-pollution) "inline" attribute from the absurdity that is:
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
to, well, [InlineHint] or [MyCompilerSvcs.InlineHint] or similar- something both quicker to type and quicker to mentally parse.
Is there any way to actually do that? Right now the only "sane" options I can see are to either add using System.Runtime.CompilerServices; (which is a pain when dealing with code behind of an ASP.NET website), adding more specific using aliases (even worse), or to keep it long-form in an accessible location for copy-paste.
Providing this question from 2009 isn't too outdated, using seems to be the only way to shorten how large the attribute reference is (as nobody suggested a more keyword-like variant for large, multifile projects). This related question was from 2010, and also suggests a using trick.
From 2015, there was this question, but it was in reference to the resulting decorations. Since what I'm interested in is the compiler directives themselves (and a performance-based one at that!) I doubt a runtime IL Emit could do this, and a "code bridge" doesn't quite naturally extend to compiler services in my mind.
Currently targeting C# 4.5, but newer versions are not forbidden.
And before "The compiler does inlining automatically!", it only does so for 32 IL Bytes or less and the inline hint overrides the size restriction. There are also other options which could be useful to have more accessible, such as NoOptimization, NoInline, and Synchronized, all of which I would very much like to not have to type absurdly long attributes to access without using statements.

You can write a Roslyn-based tool to do that. This enables to apply an attribute with a name of your choice (some short name such as AggInline) and the tool will emit the actual AggressiveInlining attribute and the required using directives. You can see the ImmutableObjectGraph tool as an example on how to do something like that in Roslyn.

Related

How determine that assembly was compiled from f# project?

What is the difference between c# and f# assemblies? Some flag maybe? I want to determine it using reflection API only
There's no single value to check that would tell you what you need, but there's a good amount of circumstancial evidence that you could look at - IlSpy is your friend if you want to explore it.
I would suggest you check for presence of these two indicators, either of them being present would mean you're likely looking at an F# assembly unless someone is really dedicated to mess things up for you.
FSharpInterfaceDataVersionAttribute on the assembly. This was my initial suggestion, however there are compiler flags that, when set, would prevent this attribute from being emitted: --standalone and --nointerfacedata. I find it highly doubtful either of them would be commonly used in the field, but the fact remains there are openly available ways of opting out from the attribute being emitted right now.
asm.GetCustomAttribute(typeof(FSharpInterfaceDataVersionAttribute))
Presence of StartupCode types. They're an artifact of how F# compiler compiles certain constructs, and it seems they're present even empty, so they should be highly reliable.
asm.GetTypes().Where(fun x -> x.FullName.StartsWith("<StartupCode$"))
In particular looking for a reference to FSharp.Core is not a great idea, as it would be commonly referenced from C# projects as well if you're working with mixed solutions (and there's nothing stopping anyone from just getting it off nuget).

Why "using namespace" directive is accepted coding practice in C#?

I am just curious to know why "using namespace" directive is acceptable in C#, though in C++ it is not. I am aware that C++ and C# are different, but my guess is C++ and C# come almost from same family, and should be using the same ideas for namespace resolution. C++ and C# both have an alias keyword to get around the namespace clash.
Can anybody point me, what I am not reading between lines in C# that makes it acceptable to use "using namespace" directive, and avoid the problems that C++ cannot.
In C++, if you write using namespace in a header, then it will be in effect for anyone who includes that header. This makes it pretty much unusable in headers. At that point, you might as well avoid it (at global scope) in .cpp files as well, if only for the sake of consistency, and to make moving implementations between .h and .cpp easier.
(note that locally scoped using namespace - i.e. within a function - are generally considered fine; it's just that they don't help with verbosity much)
In C#, there is nothing like #include, and the scope of a using directive will never span beyond a single .cs file. So it's pretty much safe to use everywhere.
The other reason is the design of the standard library. In C++, you just have std (well, now also a few more underneath it, but they are rarely used). In C#, you have gems such as System.Collections.Generic, which is extremely verbose for something that's used very commonly. It's just much more painful to avoid using in C# than it is in C++.
To sum it up, while C# and C++ do share some common design, on the matter of code modularity (I'd assign headers, modules, namespaces all to that group), their design is very different.
For me, it comes down to the support tools. Intellisense, the quick class lookup (F1 key), and refactoring options of Visual Studio give the needed reference lookup functionality.
Also, C# has every method within a class--there are no namespace level functions.
In general a difference of C# and C++ is how compilation units are handled and specified.
C++ uses header files to publish class declarations, and needs a compilation unit where this class is implemented (defined). A using namespace <xxx> statement in header files is strongly discouraged practice for C++, because this can easily lead to namespace clashes and ambiguities when included from some client code. In your class declaration you should explicitly state what you want from other namespaces (including std).
C# has single compilation units which eases use of using namespace <xxx> statements a bit. Nevertheless I'd prefer aliasing imported namespaces, if you want to avoid tedious typing. Placing using statements in a .cs file might cause ambiguous definitions as well.
While I completely agree with others that using namespaces should not be done in headers, I think banning them in cpp files is shortsighted. If you try to adhere to organizing declarations into namespaces ‘nicely’, but then ban the usage of ‘using namespace’ altogether, the path of least resistance for coders becomes the under use of namespaces.
For instance, in the above post by Pavel Minaev, he rightfully points out the namespace difference between a common C++ namespace, ‘std’, and a C# namespace, ‘System.Collections.Generic’. If you stop to think of why they are this way, a clear answer IMO is that C++ culture frowns on using namespace, while C# does not, so in C# you accept more verbose namespaces because they are not inherently painful to use. I believe namespace organization in C# is much better than C++ largely because of this cultural difference, and better class organization and general readability are not trivial things.
To put a different way, think about what would happen to people’s file organization habits if an application required them to type fully qualified paths to load a file. They’d more likely just shove everything into a root folder to avoid the typing, not a good way to promote quality organization.
While certainly not as clean as C#’s using directive, using namespace in cpp files is an overall win.
Unless you're a language purist, it saves time and makes coding easier. Unless you're dealing with complicated systems of namespaces, it's perfectly acceptable.

Is it possible to add keyword to C# or VB.NET?

I know it might not be worth it but just for education purposes I want to know if there is a way to inject your own keywords to .NET languages.
For example I thought it's good to have C++ asm keyword in C#.
Remember I'm not talking about how to implement asm keyword but a general way to add keyword to C#.
My imagined code :
asm{
mov ax,1
add ax,4
}
So is there a way to achieve this ?
The answers which cover implementing keyword{ } suits enough for this question.
This isn't possible at the moment. However, there's a Microsoft project in development called Roslyn that can be summarised as "the compiler as a service." It allows you, amongst other things, to extend or modify the behaviour of the compiler through an API.
When Roslyn becomes available, I believe this should be something that (with caution!) is quite doable.
You can use whatever tools you would like to pre-process your code before sending it to the C# compiler. For example, you might use VS macros to do the pre-processing, mapping a given syntax that you invented into something that does compile into C# code, possibly generating an error if there is a problem. If VS macros aren't powerful enough for you then you can always use your own IDE that does whatever you code it to do to the text before sending it to the compiler.
There is no built in support in the compiler for specifying your own keywords/syntax; you would need to handle it entirely independent of the compiler.
Unfortunately this is not possible. You can't extend or alter the languages in any way.
You could in some obscure way use PostSharp to read and parse strings and transform them to custom code at compile time (a pre processor). But you would not get very happy with that, as it is very error prone and you won't get any kind of intellisense or code completion for your magic strings.
According to MSDN keywords are predefined and cannot be altered. So you can't add any, because you would need to tell the compiler how to handle them. Insofar, no you can't.

code snippets interpretation

Let's say I have a WinForm App...written in C#.
Is it possible?
After all, put my eye on Iron Python.
C# is not interpreted, so unlike javascript or other interpreted languages you can't do that natively. You can go four basic routes, listed here in order of least to most complex...
1) Provide a fixed set of operations that the user can apply. Parse the user's input, or provide checkboxes or other UI elements to indicate that a given operation should be applied.
2) Provide a plugin-based or otherwise dynamically defined set of operations. Like #1, this has the advantage of not needing special permissions like full trust. MEF might come in handy for this approach: http://mef.codeplex.com/
3) Use a dynamic c# compilation framework like paxScript: http://eco148-88394.innterhost.net/paxscriptnet/. This would, in theory, allow you to compile small c# snippets on demand.
4) Use IL Emit statements to parse code and generate your operations on the fly. This is by far the most complex solution, likely requires full trust, and is extremely error prone. I don't recommend it unless you have some very obscure requirements and sophisticated users.
The CSharpCodeProvider class will do what you want. For a (VERY outdated, but still working with a few tweaks) example of its use, check out CSI.
If you are willing to consider targeting the Mono runtime, the type Mono.CSharp.Evaluator provides an API for evaluating C# expressions and statements at runtime.

c# using declarations - more = good or bad?

edit typos
Hi,
This is possibly a moronic question, but if it helps me follow best practice I don't care :P
Say I want to use classes & methods within the System.Data namespace... and also the System.Data.SqlClient namespace.
Is it better to pull both into play or just the parent, ie...
using System.Data
using System.Data.SqlClient
or just...
using System.Data
More importantly I guess, does it have ANY effect on the application - or is it just a matter of preference (declaring both the parent and child keeps the rest of the code neat and tidy, but is that at the detriment of the application's speed because its pulling in the whole parent namespace AND then a child?)
Hope thats not too much waffle
It doesn't make any difference to the compiled code.
Personally I like to only have the ones that I'm using (no pun intended) but if you want to have 100 of them, it may slow down the compiler a smidge, but it won't change the compiled code (assuming there are no naming collisions, of course).
It's just a compile-time way of letting you write Z when you're talking about X.Y.Z... the compiler works out what you mean, and after that it's identical.
If you're going to use types from two different namespaces (and the hierarchy is largely illusional here) I would have both using directives, personally.
Click Organize->Remove Usings and Visual Studio will tell you the correct answer.
Firstly, it has no effect on the application. You can prove this by looking at the CIL code generated by the compiler. All types are declared in CIL with their full canonical names.
Importing namespaces is just syntactical sugar to help you write shorter code. In some cases, perhaps where you have a very large code file and are only referring to a type from a specific namespace a single time, you might choose not to import the namespace and instead use the fully-qualified name so it's clear to the developer where the type comes from. Still, though, it makes no difference.
Express what you mean and aim for concise, clear code - that's all that matters here. This has no effect on the application, just on you, your colleagues and your future workers brains.
Use whatever happens when write your type name and press Ctrl + .,Enter in VS.

Categories