Some interfaces have events that most implementations will never raise. For example, the WPF ICommand
interface has a CanExecuteChanged
event that should be raised when the command becomes enabled or disabled. Most commands are always enabled, so this event is no needed. However, the interface still requires you to implement this event.
Thus, most ICommand
implementations will look something like this:
class MyCommand : ICommand
{
public bool CanExecute(object parameter) { return true; }
public event EventHandler CanExecuteChanged;
public void Execute(object parameter) {
...
}
}
This will generate a compiler warning, “The event ‘MyCommand.CanExecuteChanged’ is never used”.
To understand why events give a warning where unused methods don’t, you must understand more about how event work. .Net events are actually an accessor pattern, just like properties. For example:
public int MyProperty { get; set; }
public event EventHandler MyEvent;
The compiler transforms this code into something resembling
private int MyProperty_BackingField;
public int get_MyProperty() { return MyProperty_BackingField; }
public void set_MyProperty(int value) { MyProperty_BackingField = value; }
private EventHandler MyEvent;
public void add_MyEvent(EventHandler value) {
// Thread-safe version of MyEvent += value;
}
public void remove_MyEvent(EventHandler value) {
// Thread-safe version of MyEvent -= value;
}
Just like the compiler generates a backing field when you create an auto-implemented property, the compiler also generates a backing field when you create a field-like event. Unlike properties, event accessors only allow you to add or remove handlers from the event. To access the delegates currently in the event (eg, to call them and raise the event), you use the private backing field. This is why you can’t raise an event from outside the class that defines it – the backing field is private
. To be more precise, the name MyEvent
resolves to the backing field when used inside the class, and refers to the event (the accessor pair) when used elsewhere.
It is this auto-generated field the compiler is warning you about. Unlike an empty method (or a non-auto property with empty accessors), this backing field will needlessly waste memory for every instance of the class that you create. Therefore, just like any other field, the compiler will give you a warning if you never use the field.
To solve this warning, you need to get rid of the field. You can do that by explicitly defining event accessors that don’t do anything:
public event EventHandler MyEvent {
add { }
remove { }
}
Note that you should not make a field-like event virtual
; the compiler does not handle overridden field-like events gracefully.
Other posts
-
Or, torturing compilers for fun and profit. I recently tweeted an interesting C# challenge: C#...
-
When writing code that deals with security or cryptography, there are a number of mistakes...
-
Web authentication systems have evolved over the past ten years to counter a growing variety...
-
_This post is part of a [series](/#code-snippets) of blog posts called code snippets. These blog...
-
_This post is part of a [series](/#code-snippets) of blog posts called code snippets. These blog...
-
_This post is part of a [series](/#code-snippets) of blog posts called code snippets. These blog...
-
_This post is part of a [series](/#code-snippets) of blog posts called code snippets. These blog...
-
_This post is the beginning of a new [series](/#code-snippets) of blog posts called code snippets....
-
[Last time](/2015-06-10/advanced-promise-usage), I described more advanced patterns for complicated workflows involving asynchronous operations. These patterns...
-
[Last time](/2015-01-08/comparing-different-languages-promises-frameworks), I listed standard & third-party promise libraries in popular languages, comparing how each...
-
[Last time](/2015-04-01/typename-comments-a-new-kind-of-comment), I introduced a new syntax for code comments, typename comments. April Fools! However,...
-
C# has two well-known styles of comments: C-style comments (`/* ... */`) and C++-style comments...
-
How many times have you seen code like this? ```csharp if (someSequence.Count() > 2) {...
-
[Last time](/2015-01-05/introducing-promises), I explained what promises are and how they work. Now, I'll explore standard...
-
[Last time](/2015-01-04/async-method-patterns), I explored the two main options for writing asynchronous functions. Now, I'll describe...
-
[Last time](/2014-12-23/parallelism-async-threading-explained), I explained the basic concepts of asynchronous and multi-threaded programming. As I explained...
-
Concurrent programming techniques, such as multi-threading or asynchronous operations, are all the rage nowadays. As...
-
# Background Both Visual Studio and Roslyn use the [Managed Extensibility Framework](https://mef.codeplex.com/) (MEF) to build...
-
Visual Studio 2010 rewrote the entire shell UI – the MDI tabs & tool windows,...
-
As I've described [earlier]({% post_url 2013-11-10-extending-visual-studio-part-2-core-concepts %}), when creating a Visual Studio extension, you are...
-
[Last time]({% post_url 2014-05-21-exploring-roslyn-part-2-inside-end-user-preview %}), I talked about what the Roslyn End-User Preview does and...
-
[Last time]({% post_url 2014-04-07-exploring-roslyn-part-1-introduction %}), I described the basics of the Roslyn compiler platform, including...
-
The .Net Compiler Platform, codenamed "Roslyn", is the most ambitious project from Microsoft's Developer Division...
-
Errors are one of the most common and annoying problems in programming. Whether it's the...
-
After four exciting years, I am regretfully leaving the [Microsoft MVP program](http://mvp.microsoft.com/). I have greatly...
-
[Last time]({% post_url 2014-02-25-extending-visual-studio-part-4-writing-cross-version-extensions %}), I talked about how to write Visual Studio extensions that...
-
[Last time]({% post_url 2014-02-21-extending-visual-studio-part-3-assembly-versioning %}), I talked about the different approaches that Visual Studio takes...
-
The new [.Net Reference Source Browser](http://referencesource-beta.microsoft.com/) (see my [previous post]({% post_url 2014-02-24-inside-the-new-net-reference-source %})) is an...
-
Seven years ago, Microsoft released the .Net Reference Source Code, containing source for much of...
-
[Last time]({% post_url 2013-11-10-extending-visual-studio-part-2-core-concepts %}), I talked about the core concepts and basic assemblies within...
-
When using Visual Studio, it can ocasionally be useful to have separate “profiles” – to...
-
One of Gmail's many useful features is "Send mail as", which lets you use a...
-
.Net's [assembly resolver](http://msdn.microsoft.com/en-us/library/yx7xezcf) (Fusion) takes assembly names (eg, `MyCompany.MyProduct, Version=2.1.0.0, , Culture=neutral, PublicKeyToken=3bf5f017df1a30a5`) and resolves...
-
After over two months of work, I rewrote the Markdown editor in [Web Essentials](http://vswebessentials.com/) to...
-
This post
-
My previous post described how to get started writing Visual Studio extensions. This post will...
-
In addition to being an excellent development environment, Visual Studio also has a powerful extensibility...
-
.Net has three low-level mechanisms to run code in parallel: Thread, ThreadPool, and Task. These...
-
One of the less-documented features of the LESS language is the ampersand selector, which refers...
-
Javasript is not a traditionally object-oriented programming languague. Wikipedia describes Javascript as a ”scripting, object-oriented...
-
After upgrading to Jekyll 1.1, you may notice that posts that used to work fine...
-
As I mentioned last time, the best way to create simple thread-safe lock-free data structures...
-
Last time, I showed how to create a simple covariant immutable stack. One of the...
-
Last time, I showed how to create a simple immutable stack. However, this stack is...
-
Last time, I explained the basic meaning of immutability. The simplest useful example of an...
-
A read-only object is an object that does not expose any way to change it....
-
Last time, we saw how to write about Jekyll tags in Jekyll-based blog posts, using...
-
Jekyll is a very nice system for writing blogs. However, it does have some shortcomings,...
-
The next step in migrating my blog to Jekyll was to convert the code blocks...
-
The first step in my migration to Jekyll was to import my old posts into...
-
My new design is powered by Jekyll and LESS (the LESS does as much or...
-
After nearly a year of inactivity, I have finally returned to my blog. I had...
-
If you open an older ASP.Net MVC3 project in Visual Studio 2012, you may see...
-
Last year, Microsoft announced a simple new feature in C# 5: Caller Info Attributes. These...
-
If you use the ASP.Net MVC 3 [Compare] validation attribute on a model property, then...
-
CSRF attacks are one of the many security issues that web developers must defend against. ...
-
What’s wrong with the following code? var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);...if (names.Contains(sqlCommand.ExecuteScalar()) This code is...
-
One common misconception about web security is that protecting important actions with CAPTCHAs can prevent XSS...
-
One of the most useful additions to the .Net 4.0 base class library is the...
-
ASP.Net MVC uses the new (to ASP.Net 3.5) Http*Base wrapper classes (HttpContextBase, HttpRequestBase, HttpResponseBase, etc)...
-
People sometimes wonder why C# 5 needs to add caller info attributes, when this information...
-
UPDATE: Now that the Visual Studio 11 beta has shipped with this feature implemented, I...
-
UPDATE: Now that the Visual Studio 11 beta has shipped with this feature implemented, I...
-
UPDATE: Now that the Visual Studio 11 beta has shipped with this feature implemented, I...
-
One common question about ASP.Net MVC is how to make “default” controller. Most websites will...
-
Update: This bug was fixed in XRegExp 1.5.1. However, as far as I know, there...
-
Part 1 is here Some languages have better ways to pass boolean parameters. C# 4.0,...
-
Have you ever written code like this: public void UpdateLayout(bool doFullLayout) { //Code if (doFullLayout)...
-
C# is usually touted as a type-safe language. However, it is not actually fully type-safe!...
-
Until now, I've been focusing on only one of the differences between delegates and function...
-
When working with large .Net applications, it can be useful to find out where event...
-
A .Net event actually consists of a pair of accessor methods named add_EventName and remove_EventName. ...
-
Sometimes, it can be useful to make an extension method specifically for a single block...
-
Unlike WinForms or native Win32 development, WPF provides a rich layout model which allows developers...
-
This is part 5 in a series about state and function pointers; part 1 is...
-
This is part 4 in a series about state and function pointers; part 1 is...
-
.Net supports two kinds of delegates: Open delegates and closed delegates. When you create a...
-
This is part 3 in a series about state and function pointers; part 1 is...
-
This is part 2 in a series about state and function pointers; part 1 is...
-
Most languages – with the unfortunate exception of Java – allow functions to be passed...
-
Many people write ForEach extension methods for MVC WebForms views, which take a sequence and...
-
Razor’s inline helpers allow you to create lambda expression that return markup (as a HelperResult). ...
-
In addition to normal and static helpers, Razor supports inline helpers, (also known as templates),...
-
Razor helpers can be extremely useful, but they are designed to be used only by...
-
The Boot Camp drivers in the latest generation of MacBook Pros now expose more of...
-
We’ll continue our trek into Razor’s class-level features with helpers. Helpers are one of Razor’s...
-
After looking at how Razor’s Execute() method is generated, we will turn to class-level features....
-
Last time, we saw how basic Razor constructs are translated into C#. We can see...
-
After looking at the various assemblies in the WebPages framework, we will drill into the...
-
Last time, we saw how standalone Razor pages are served. MVC3 maintains the strict separation...
-
Last time, we saw that ASP.Net Web Pages are implemented in two independent assemblies. These...
-
Razor involves two distinct components: The Razor engine and the WebPages framework. The Razor engine,...
-
jQuery makes it very easy to modify a DOM tree. For example, to strip all...
-
Last time, we saw that there are severe limitations in creating ASPX pages which inherit...
-
ASP.Net pages can inherit from custom classes (as long as they inherit System.Web.UI.Page). This can...
-
.Net developers frequently need to build connection strings, especially when connecting to Access or Excel...
-
One of the unique features of ASP.Net WebPages (formerly Razor) is automatic HTML encoding. All...
-
C# 4.0 adds support for optional parameters. The following code prints 4: static void Main()...
-
The new ASP.Net WebPages view engine (formerly Razor) allows you to create reusable parameterized blocks...
-
.Net DataTables can be very useful when writing data-driven applications. However, they have one limitation:...
-
When designing fluent APIs, one issue that comes up is partial type inference. If a...
-
A common chore in developing real-world C# applications is implementing value semantics for equality. This...
-
Last time, we saw that the this parameter to an instance method in a struct...
-
Usually, you cannot pass ref this as a parameter, since this is not a writable...
-
VB.Net’s Nothing keyword is is not the same as C#’s null. MSDN states, “Assigning Nothing...
-
jQuery contains a powerful and flexible animation engine. However, it has some limitations, primarily due...
-
A generic class can specify that its generic parameter must inherit a type. However, there...
-
In part 1, we discussed the simple approach to making a nested iterator. However, we...
-
C# 2.0 introduced a powerful feature called an iterator, a method which returns an IEnumerable<T>...
-
My previous post stretched the limit of simple copy prevention. Beyond this point, it gets...
-
The methods discussed in my previous post are crude and ugly. Most of the time,...
-
Many web developers like to prevent their viewers from copying their text. While I do...