Is there any way to disable the use of the "dynamic" keyword in .net 4?
I thought the Code Analysis feature of VS2010 might have a rule to fail the build if the dynamic keyword is used but I couldn't fine one.
It's part of the C# 4.0 language, so no not really.
You can use FXCop to look for it though and fail the build if it encounters it.
Style cop might work instead:
http://code.msdn.microsoft.com/sourceanalysis
Here is a link talking about the same issue and how style cop might be the answer. There is also a post about how to get FX cop to potentially look for the dynamic keyword, although it's not perfect.
http://social.msdn.microsoft.com/Forums/en/vstscode/thread/8ce407ba-bdf7-422b-bbcd-ca4701c3a76f
The dynamic keyword is not evil, but using it could be.
It leads to code errors that you can only find during runtime.
This should be avoided at all costs.
Runtime errors are bad. Compile time errors are good.
You could use something like the following to set your own standards.
http://joel.fjorden.se/static.php?page=CodeStyleEnforcer
Target .net 1.0? :-)
Or do code reviews.
(Or, to be less facetious, it should be pretty easy to write a custom FxCop or CA rule to disallow use of dynamic)
Wouldn't you just kill for a C++ macro right now? :-)
Remove the reference to Microsoft.CSharp.dll, and I think maybe all uses of dynamic will fail to compile.
I'm not sure I understand what this irrational fear of the dynamic keyword is for. There was this type of hysteria over anonymous variables and the var keyword for .NET 3.5 except that was just idiotic since those are legitimate statically defined types.
The dynamic keyword serves a highly specialized purpose, I don't see why any person would have the desire to use it without understanding why. However stopping that from occurring could be solved with 1 team meeting explaining some of the new features of .NET 4 including the dynamic keyword. I assume you're more of a senior or the senior lead of the team; it should be quite easy to tell your team if they ever feel they NEED to use the dynamic keyword to come see you FIRST.
This was exactly the instructions I gave to my team as I find it unlikely we will ever use the dynamic keyword because we don't write COM interop activity. And past that I will defer any type of dynamic proxy use to an established library like Linfu or Castle and leave up the implementation of dynamic proxies to them to use or not use the dynamic keyword.
Related
I'm trying to make a Xamarin.Android app that highlights the syntax of many different languages. I plan to use ANTLR to deal with most of them, but for C# I want to use Roslyn as that will undoubtedly be faster and less buggy than ANTLR.
What is the best way to implement syntax highlighting with Roslyn? For highlighting Java syntax, the approach I took was parsing the text into a parse tree, and using a visitor to color the text associated with each terminal. You can view my code here. Is this also a good idea for Roslyn, or does Roslyn provide APIs for syntax highlighting? (e.g. Does the code behind syntax highlighting in Visual Studio live in the dotnet/roslyn repo?) I'd really prefer not to reinvent the wheel, but I will if I have to.
edit: I have accepted Tamas' answer because his solution is the most practical for my use case; I do not have access to the full solution to build a semantic model with, so I will have to do some of my own analysis. However, if your app supports more broad C# integration and can build a semantic model, take a look at the Roslyn Classification APIs which are used in Jonathon Marolf's answer.
the ConsoleClassifier project in the roslyn Samples should be a good starting place.
Did you have a look at SourceBrowser? If you can do a full solution build, then I would use the same approach.
If your context doesn't allow a full build, then you can implement something relatively good based on syntax token types. However you might have to handle some corner cases, like contextual keywords, var, implicitly declared local variables (like value), etc. Have a look at what SonarQube is using.
Similarly, you can look for other tools that you know are Roslyn based, like OmniSharp. I'm not sure if that uses regex or Roslyn to do the highlighting. But in any case you could get quite far with Regex too.
We have recently started using FxCop on our code base and I am in the process of evaluating the problems. One is the IdentifiersShouldNotMatchKeywords issue. This applies to a namespace company.blah.Event, which it wants me to change to something else as event is a keyword. The docs say:
When to Suppress Warnings
Do not suppress a warning from this rule. The library might not be usable in all available languages in the .NET Framework.
under what circumstances might it not be available? Do I need to change this? I imagine that it is not going to be very popular.
Different languages have different keywords. For example I can use If as a variable in C#, but if someone loads up the project in VB, they're screwed, any case like that can cause problems.
I'd change it, just to be safe. I'd say you need to change it if anyone else is consuming your library, you can't know what language they're going to use when doing so.
Well, it is a bit of a screwy message. It proclaims to know what the keywords will be in an as-yet unwritten language. For all you know, a future language like BrainFart may use Acme as a keyword, and you're screwed because that happens to be your company name.
There is a notable difference between the Acme and Event keywords though. The author of the BrainFart language will point out that you should have known about Event being a problem from running your code through FxCop. She'll win that argument.
You'd better change it.
Yes I know that it shouldn't be abused and that C# is primariy used as a static language. But seriously folks if you could just dirty up some code, in the python style, or create some dynamic do hicky, would you?
My mind is working overtime on this having spent a while loving the dynamics of python, is c# going over to the dark side through the back door?
Is the argument for static typing a dead one with this obvious addition?
Is the argument for less Unit testing a bit silly when we are all grown ups?
Or has the addition of dynamics ruined a strongly static typed and well designed language?
I lost the desire to use dynamic types when I started using type inference.
C# has expanded to including some aspects of dynamic typing, yes, but that doesn't mean that static typing is dead. It simply means that C# has added some tools that allow developers of all persuasions to solve all kinds of problems in many different ways.
I have a problem with the concept of one type system being "better" than another. That is like saying a hammer is better than a screwdriver. Without know the context of the task at hand it is impossible to make that determination! Dynamic typing is better than static typing for certain problems and situations and vice-versa. The superiority of the approach is entirely conditional on the problem at hand.
So to stick with my tool analogy, it is best to have a toolbox that contains hammers and screwdrivers and know how to use each efficiently. This will make you a better developer as you will be best equipped to solve any problem you face. C#'s new dynamic typing additions are simply an effort to help you by providing these tools in a single, convenient package.
Is the argument for static typing a
dead one with this obvious addition?
Is the argument for less Unit testing
a bit silly when we are all grown ups?
Or has the addition of dynamics ruined
a strongly static typed and well
designed language?
For a while, languages have been moving more and more into the domain of "statically typed when possible, dynamically typed when necessary". And with structural typing (statically checked duck typing) starting to work its way into mainstream languages, we might see languages evolve to the point where they're basically statically checked Python.
For what its worth, dynamically typed code is just as mindful of types as statically typed code. Idiomatic C# is still statically typed, and will remain that way for a long time to come.
As I understand it, the dynamic keyword was introduced more to facilitate interop and method invocation on unknown types at runtime rather than the kind of dynamic typing you find in languages like python.
Essentially, where you would previously have to call InvokeMember to call a method on an unknown type, you would instead create a dynamic object and just call the method, which would be resolved at runtime. The code becomes a great deal easier to read. Why would you want to call a method (or access a property) on an unknown type? Well, WPF does it all the time when you use databinding.
You also use it when you want to use an interop dll using weak binding, such as for example, if you wanted to write code that used office interop, but you wanted to support more than one version of office. I've had to do this before, and the code for it is horrendous. The dynamic keyword would make such code far easier to read and understand.
See this article for more info:
http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx
As far as i remember, type errors is about 5-10% of all found errors, so we have fewer errors for languages with static typing for free. Unit and regression tests is also a few smaller for static typing.
Dynamic typing is nice for OO languages. In case of FP language (and with HM type system especially) dynamic vs static typing don't impact your decisions of program design at large.
But there is moment where you want nice code performance and that moment will show dark side of dynamic types to you.
Yes.
No.
No.
Yes.
No.
Strong typing is still the best way to go for large projects. Not only does it make code completion (IntelliSense) much better, but it can tell you obvious problems at compile time. For example, say socket.Write takes a string. In C# you won't be able to run your program if you try to pass it a number, while in Python you would only find out about your bug when your program crashes.
On the other hand, it's easy to imagine how useful it would be to have a JSON parser that acts like an expando object, automatically growing the properties specified in the JSON.
To elaborate my point a bit, I think C# will mostly stay safe from the evils of dynamic typing, while still reaping its benefits. This is because the system still encourages types on everything, as opposed to other dynamic languages where types are entirely optional (or even just advisory). In C# you will be able to just "git 'er done" with duck typing, expando properties, and other dynamic typing goodness, but it will be well-marked with the dynamic keyword which helps you to keep it self-contained.
I am currently developing an application where you can create "programs" with it without writing source code, just click&play if you like.
Now the question is how do I generate an executable program from my data model. There are many possibilities but I am not sure which one is the best for me. I need to generate assemblies with classes and namespace and everything which can be part of the application.
CodeDOM class: I heard of lots of limitations and bugs of this class. I need to create attributes on method parameters and return values. Is this supported?
Create C# source code programmatically and then call CompileAssemblyFromFile on it: This would work since I can generate any code I want and C# supports most CLR features. But wouldn't this be slow?
Use the reflection ILGenerator class: I think with this I can generate every possible .NET code. But I think this is much more complicated and error prone than the other approaches?
Are there other possible solutions?
EDIT:
The tool is general for developing applications, it is not restricted to a specific domain. I don't know if it can be considered a visual programming language. The user can create classes, methods, method calls, all kinds of expressions. It won't be very limitating because you should be able to do most things which are allowed in real programming languages.
At the moment lots of things must still be written by the user as text, but the goal at the end is, that nearly everything can be clicked together.
You my find it is rewarding to look at the Dynamic Language Runtime which is more or less designed for creating high-level languages based on .NET.
It's perhaps also worth looking at some of the previous Stack Overflow threads on Domain Specific Languages which contain some useful links to tools for working with DSLs, which sounds a little like what you are planning although I'm still not absolutely clear from the question what exactly your aim is.
Most things "click and play" should be simple enough just to stick some pre-defined building-block objects together (probably using interfaces on the boundaries). Meaning: you might not need to do dynamic code generation - just "fake it". For example, using property-bag objects (like DataTable etc, although that isn't my first choice) for values, etc.
Another option for dynamic evaluation is the Expression class; especially in .NET 4.0, this is hugely versatile, and allows compilation to a delegate.
Do the C# source generation and don't care about speed until it matters. The C# compiler is quite quick.
When I wrote a dynamic code generator, I relied heavily on System.Reflection.Emit.
Basically, you programatically create dynamic assemblies and add new types to them. These types are constructed using the Emit constructs (properties, events, fields, etc..). When it comes to implementing methods, you'll have to use an ILGenerator to pump out MSIL op-codes into your method. That sounds super scary, but you can use a couple of tools to help:
A pre-built sample implementation
ILDasm to inspect the op-codes of the sample implementation.
It depends on your requirements, CodeDOM would certainly be the best fit for a "program" stored it in a "data model".
However its unlikely that using option 2 will be in any way measurably slower in comparision with any other approach.
I would echo others in that 1) the compiler is quick, and 2) "Click and Play" things should be simple enough so that no single widget added to a pile of widgets can make it an illegal pile.
Good luck. I'm skeptical that you can achieve point (2) for anything but really toy-level programs.
Actually, maybe not full-blown Lex/Yacc. I'm implementing a command-interpreter front-end to administer a webapp. I'm looking for something that'll take a grammar definition and turn it into a parser that directly invokes methods on my object. Similar to how ASP.NET MVC can figure out which controller method to invoke, and how to pony up the arguments.
So, if the user types "create foo" at my command-prompt, it should transparently call a method:
private void Create(string id) { /* ... */ }
Oh, and if it could generate help text from (e.g.) attributes on those controller methods, that'd be awesome, too.
I've done a couple of small projects with GPLEX/GPPG, which are pretty straightforward reimplementations of LEX/YACC in C#. I've not used any of the other tools above, so I can't really compare them, but these worked fine.
GPPG can be found here and GPLEX here.
That being said, I agree, a full LEX/YACC solution probably is overkill for your problem. I would suggest generating a set of bindings using IronPython: it interfaces easily with .NET code, non-programmers seem to find the basic syntax fairly usable, and it gives you a lot of flexibility/power if you choose to use it.
I'm not sure Lex/Yacc will be of any help. You'll just need a basic tokenizer and an interpreter which are faster to write by hand. If you're still into parsing route see Irony.
As a sidenote: have you considered PowerShell and its commandlets?
Also look at Antlr, which has C# support.
Still early CTP so can't be used in production apps but you may be interested in Oslo/MGrammar:
http://msdn.microsoft.com/en-us/oslo/
Jison is getting a lot of traction recently. It is a Bison port to javascript. Because of it's extremely simple nature, I've ported the jison parsing/lexing template to php, and now to C#. It is still very new, but if you get a chance, take a look at it here: https://github.com/robertleeplummerjr/jison/tree/master/ports/csharp/Jison
If you don't fear alpha software and want an alternative to Lex / Yacc for creating your own languages, you might look into Oslo. I would recommend you to sit through session recordings of sessions TL27 and TL31 from last years PDC. TL31 directly addresses the creation of Domain Specific Languages using Oslo.
Coco/R is a compiler generator with a .NET implementation. You could try that out, but I'm not sure if getting such a library to work would be faster than writing your own tokenizer.
http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/
I would suggest csflex - C# port of flex - most famous unix scanner generator.
I believe that lex/yacc are in one of the SDKs already (i.e. RTM). Either Windows or .NET Framework SDK.
Gardens Point Parser Generator here provides Yacc/Bison functionality for C#. It can be donwloaded here. A usefull example using GPPG is provided here
As Anton said, PowerShell is probably the way to go. If you do want a lex/ yacc implementation then Malcolm Crowe has a good set.
Edit: Direct Link to the Compiler Tools
Just for the record, implementation of lexer and LALR parser in C# for C#:
http://code.google.com/p/naive-language-tools/
It should be similar in use to Lex/Yacc, however those tools (NLT) are not generators! Thus, forget about speed.