Why C# does not have Handles clause like VB? - c#

In VB, we have the Handles clause, that allows add a Handler to an event of a control without putting it into the xaml file (directly into the VB file).
xaml:
<Button x:Name="myButton" />
VB:
Private Sub Button_Click() Handles myButton.Click
End Sub
One good thing that can be done using this is the possibility to use the Visual Studio dropdowns to add events automatically without the need to go to the xaml file and change it. Read this question (and the answer) to better understand what I'm talking about:
Visual studio 2010 showing available events from code behind
The answer of that question doesn't specify why C# does not have this feature inside Visual Studio, but it's clear for me: C# does not have this feature because it uses the Handles clause to add the event on CodeBehind.
I know that we can make use of the += and add the event manually on the constructor, below InitializeComponent (that is almost the same thing), but VB also have the AddHandler that can add events on the constructor (and in other places), and it's not automatic and less reliable (for me) than the Handles clause.
My question is:
Why it's never implemented? It's non-reliable? Non-secure? There's any workaround?

It was never implemented because no one at Microsoft thought it was useful enough to justify the effort. The exact reasons why can only be answered by someone on the C# team. And while it's true that C# and VB have made an effort to synchronize their features, that doesn't mean they're going to retroactively introduce all VB-specific features in C# or vice versa. (Note that the Handles clause has always existed in VB.NET)
However, one can speculate based on VB's history as a language why it might have been introduced. Namely, that's how VB events pre-NET always worked, so VB developers would probably be used to it.
In traditional VB, events were wired up to objects by name. If you have a Form and you define a subroutine named Form_Load, it will run as your form's Load event. This tradition carried over into ASP, and still lingers as the AutoEventWireup configuration option. VB developers were used to the language knowing what method to run for which events without having to "explain it" to the compiler.
In .NET languages, events are just a particular kind of property with a special type (a delegate type) that have to be assigned like any other property. In order to allow VB developers to transition easily into VB.NET, though, you would ideally give them an easy way to do so without having to learn about events and delegates and handlers (at least not immediately). The Handles keyword accomplishes this -- you just tack on Handles Load onto your Form_Load sub and it becomes an event handler.
C#, on the other hand, has no legacy behavior that it needed to maintain. The target audience for C# consisted of people from many languages, most of which had no built-in concept of events and certainly did not have the auto-wireup behavior of VB. So there was no need to introduce this behavior into the language, but instead, new C# developers would just learn the "right way" of doing things from the start.
With the introduction of WPF and MVVM view/model separation and the push for minimal code-behind, a handles keyword becomes a bit more attractive, but it still seems to go against the general principles of how C# handles events. I suspect it would take a very, very strong argument to convince the C# team that it was worth implementing.

Related

VS2017 C# versus VB creating events

I'm trying to get up to speed with C# after years of writing VB code.
I'm trying to add new events in my code. In VB the list of available events is easily accessible but that's not the case in C# and I don't understand the reason for the difference.
I've looked in several books trying to find an explanation for this to no avail.
Can someone please tell me the reason for the difference and/or is there an easy way to add new events to my C# code?
In VB the list of available events is easily accessible but that's not the case in C# and I don't understand the reason for the difference.
Yes, this is a very well known difference between the two languages, which makes working with events much easier in VB than C#.
Can someone please tell me the reason for the difference and/or is there an easy way to add new events to my C# code?
There is no logical reason except that the two languages are done by two different teams who didn't really communicate much and made different decisions. VB has been always making things as easy as possible and doable in GUI. C# on the other hand, targeted more experienced developers who usually favored typing and shortcuts over using GUI.
If you prefer GUI over typing, the easiest way to do it in C# is to select the form or control, open its properties, switch to the list of events, and then double click on the event that you want. This will automatically switch to the code and insert the event boilerplate for you similar to VB.
For the default events (e.g. OnClick), you can simply double click on the form or control in the design mode which will do the above.
Alternatively, switch your Design view to Source view, go to the form or control tag and type the event that you want, it will automatically add ="" for you. Click between the double-quotes, and select the default event name and it will do the above.

Creating Inline Functions and Macros

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...
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");
}
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.

VB.NET for a C# Developer

I may be starting a new job which requires VB.NET but I am a C# developer and even though I may be able to understand the code, writing it from scratch seems to be a hassle for me for a while.
There are C#>VB.NET converter out there (online) and where you paste your C# code and it converts it into VB.NET code. My question is whether there is any person who experienced this and whether it is a good temp solution or I am gonna experience so much difficulties with that? Do they convert good?
And probably I am gonna run the codes on Asp.net.
An example converter: http://www.developerfusion.com/tools/convert/csharp-to-vb/
Thanks in advance.
Don't use converters - learn VB.NET and the differences between its syntax and C#.
There is a very good comparison cheat sheet here to get you started.
In practice, you will find that most of the time you are interacting with familiar .NET objects in the same way and you only have some syntax differences (though generics and delegate syntax are such a pain that one tends to shy away from them).
Microsoft has stated that they are trying to bring both language to feature parity, so anything you can do in C#, you should be able to do with VB.NET (with minor differences normally).
Update - don't forget that compiled code (in assemblies) should work identically in both languages (assuming CLS compliance), so you could write a library in C# for use with VB.NET and vice versa.
You can try the Telerik Code Converter
That being said, it would be a valuable exercise to convert the code manually. You'll gain a good amount of experience by doing a manual conversion and you'll learn some of the key differences between the 2 languages that may help you going forward.
I'd say your code will work, but you'll miss some special features for which there is no C# equivalent and which would make your code fit better with the language. Some examples:
In C#, you assign event handlers with +=, which will be translated to AddHandler. In VB, however, it's much more common to use WithEvents instance variables. This is especially relevant for ASP.NET, where C# often uses the AutoEventWireup feature, which done in VB through WithEvents instead.
In C#, you access XML through LINQ to XML method calls, which will be translated to the matching method calls in VB. However, in VB, it's more natural to use the integrated language support for XML.
This is good for converting the bulk of your code, but it's not a total solution. One thing you will have issues with is the converter knowing what to do with C#'s indexer brackets ([]) vs. method parentheses (()). VB uses parenthesis for indexers and methods and there's no way for it to know which to use.
I've gone through conversion hell with these things and finally decided that they were just too much trouble and that it was much easier to just convert it by hand. I come from a VB background, so this wasn't a huge deal for me.
For what you want to do, though, you need to learn VB.NET syntax. Writing everything in C# and converting it to VB.NET is not a good, long-term solution. You will eventually have to learn VB.NET. Your manager(s) will not be keen to the fact that you're not learning the core fundamentals of the language you were hire to program in.
Don't do it... There are converters, but you will find that once you learn the key differences that you will be fine. You will interact with the .NET libraries in the same way so much of the programming will be the same.
I just changed jobs recently and went the opposite direction. I'm glad I took the time to learn C#. Major dividends in the end and you'll be more versatile.

Dynamic code generation

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.

How to recognize code generated by Visual Studio's GUI designer?

Visual Studio is kind enough to generate a lot of code for us when we create and design Windows.Forms controls. It also surrounds most of it with a #region statement.
In newer versions it also uses a partial class to separate generated from manually created code.
Developers are supposed to edit code only in certain areas.
But nothing prevents us from violating this in whatever way we please.
I'm fine with manual edits that could just as well have been made from the designer, or manual edits in areas the designer doesn't touch. But I'd like to flag any other kind of edit.
Does anyone know a utility that can do this? StyleCop rules perhaps?
I mostly need it for the combination of C#, Windows.Forms, and Visual Studio 2003, 2005, and 2008.
These days, designer code should end up in a .Designer.cs file. It should be very rare that developers need to touch that. Unfortunately, I don't know any way of verifying that the code was genuinely generated by the designer. It would be handy if it included some sort of hash, but it doesn't as far as I'm aware...
Given how easy it is now to just say "don't edit designer files" do you really need another system though? It's not like you need to stay away from specific regions - it's the whole file which is out of bounds.
Why should developers not be allowed to change this code? If they are able to write code that works, they should be allowed to do it. If they are not able to write code that works, lets say they should be trained or fired.
You just have to extend the meaning of "it works" to "it works at runtime as well as in the designer". So what's wrong about that?
Todays gui designers are not very restrictive and are doing a good job in "understanding" code that had been written by a human.
There is also real generated code around, for instance code generated by some xml specification, resources etc. This code is generated when building, so when it had been changed, these changes are undone whenever the application is built.
Designers are not real code generators of this kind. They are a kind of "coding helpers", helping the developer to write code faster then by typing it in. But it should actually be possible to write the same kind of code manually although limiting one self to the designers capabilities is a reasonable maintainability decision.

Categories

Resources