|
The C# team posts answers to common questions
-
Use the using directive to create an alias for a long namespace or class name.
You can then use it anywhere you normally would have used that class or
namespace. The using alias has a scope within the namespace you declare it in. Sample code:
// Namespace:
using act = System.Runtime.Remoting.Activation;
// Class:
using list = System.Collections.ArrayList;
...
list l = new list(); // Creates an ArrayList
act.UrlAttribute foo; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute foo
[Author: Jon Skeet]
|
-
This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of
the object that the reference refers to is used to decide which method implementation to use. When a method
of a base class is overridden in a derived class, the version in the derived class is used, even if the calling
code didn’t “know” that the object was an instance of the derived class. For instance:
public class Base
{
public virtual void SomeMethod()
{
}
}
public class Derived : Base
{
public override void SomeMethod()
{
}
}
...
Base b = new Derived();
b.SomeMethod();
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod . Now,
if you use the new keyword instead of override , the method in the derived class
doesn’t override the method in the base class, it merely hides it. In that case, code like this:
public class Base
{
public virtual void SomeOtherMethod()
{
}
}
public class Derived : Base
{
public new void SomeOtherMethod()
{
}
}
...
Base b = new Derived();
Derived d = new Derived();
b.SomeOtherMethod();
d.SomeOtherMethod();
Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4).
They’re effectively two entirely separate methods which happen to have the same name, rather than the derived method
overriding the base method.
If you don’t specify either new or overrides , the resulting output is the same
as if you specified new , but you’ll also get a compiler warning (as you may not be aware that you’re
hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to
include the keyword).
That provides the basics of overriding and the difference between new and override ,
but you should really see a book or tutorial for a more in-depth look at polymorphism.
[Author: Jon Skeet]
|
-
Checked exceptions are a very hotly debated topic in some circles, particularly for experienced Java developers moving to, or additionally learning, C#. Here are some resources that discuss the issue in depth:
Note that without the CLR itself supporting checked exceptions, it would be effectively impossible for C# to do so alone.
[Author: Jon Skeet]
|
-
Using the as operator differs from a cast in C# in three important ways:
- It returns
null when the variable you are trying to convert is not of
the requested type or in it’s inheritance chain, instead of throwing an exception.
- It can only be applied to reference type variables converting to reference types.
- Using
as will not perform user-defined conversions, such as implicit or
explicit conversion operators, which casting syntax will do.
There are in fact two completely different operations defined in IL that
handle these two keywords (the castclass and
isinst instructions) – it’s not
just “syntactic sugar” written by C# to get this different behavior. The
as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft’s
CLR compared to casting (even in cases where there are no invalid casts
which would severely lower casting’s performance due to exceptions).
[Author: Jon Skeet]
|
-
C# defines a number of aliases for CLR types. They may be used interchangably, and even mixed together, e.g.
string x = new System.String(' ', 5); .
These are the aliases defined:
Alias |
CLR type |
string |
System.String |
sbyte |
System.SByte |
byte |
System.Byte |
short |
System.Int16 |
ushort |
System.UInt16 |
int |
System.Int32 |
uint |
System.UInt32 |
long |
System.Int64 |
ulong |
System.UInt64 |
char |
System.Char |
float |
System.Single |
double |
System.Double |
bool |
System.Boolean |
decimal |
System.Decimal |
[Author: Jon Skeet]
|
-
Put simply, an event gives more limited access than a delegate. If an event is made public, code in
other classes can only add or remove handlers for that event; they can’t necessarily fire it, find out
all the handlers for it, or remove handlers they don’t know about. Events also allow more flexibility in
terms of how the handlers are stored. For more details on this, see
Eric
Gunnerson’s article on the topic.
[Author: Jon Skeet]
|
-
All constants declarations are implicitly static, and the C# specification states that the
(redundant) inclusion of the static modifier is prohibited. I believe this is to avoid the
confusion which could occur if a reader were to see two constants, one declared static and one not – they
could easily assume that the difference in specification implied a difference in semantics. Having said
that, there is no prohibition on redundantly specifying an access modifier which is also the default one,
where there is a choice. For instance, a (concrete) method can be explicitly marked as private despite that being the
default. The rule appears to be that where there is no choice (e.g. a method declaration in an interface)
the redundant modifier is prohibited. Where there is a choice, it’s allowed.
[Author: Jon Skeet]
|
-
C# defines the following character escape sequences:
\' – single quote, needed for character literals
\" – double quote, needed for string literals
\\ – backslash
– Unicode character 0
\a – Alert (character 7)
\b – Backspace (character 8)
\f – Form feed (character 12)
\n – New line (character 10)
\r – Carriage return (character 13)
\t – Horizontal tab (character 9)
\v – Vertical quote (character 11)
\uxxxx – Unicode escape sequence for character with hex value xxxx
\xn[n][n][n] – Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
\Uxxxxxxxx – Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)
Of these, \a , \f , \v , \x and \U are rarely used in my experience.
[Author: Jon Skeet]
|
-
A string literal such as @"c:\Foo" is called a verbatim string literal. It basically means,
“don’t apply any interpretations to characters until the next quote character is reached”. So, a verbatim
string literal can contain backslashes (without them being doubled-up) and even line separators. To get a
double-quote ( " ) within a verbatim literal, you need to just double it, e.g.
@"My name is ""Jon""" represents the string My name is "Jon" . Verbatim string literals
which contain line separators will also contain the white-space at the start of the line, so I tend
not to use them in cases where the white-space matters. They’re very handy for including XML or SQL in your source
code though, and another typical use (which doesn’t need line separators) is for specifying a file system path.
It’s worth noting that it doesn’t affect the string itself in any way: a string specified as a verbatim string literal
is exactly the same as a string specified as a normal string literal with appropriate escaping. The debugger will
sometimes choose to display a string as a verbatim string literal – this is solely for ease of viewing the string’s
contents without worrying about escaping.
[Author: Jon Skeet]
|
-
By default, all parameters are passed by value in C#. Parameters are only passed by reference if you explicitly include
an out or ref modifier. However, you need to be aware that when the type of the
parameter is a reference type, you’re passing a reference rather than an actual object. For more information, see my
article on parameter passing and
the C#
Programmer’s Reference.
[Author: Jon Skeet]
|
-
Although C# doesn’t have templates, and isn’t likely to get them, it is
getting a feature called generics which will be available in the next version
of .NET and Visual Studio. Generics will be a feature in the CLR itself,
and most languages targetting the CLR will change to support it. Generics provide a
lot of the functionality of C++ templates (mostly in terms of type safety) but in a more
restricted (and therefore potentially less confusing) way.
For more information, see:
[Author: Jon Skeet]
|
-
Many people, including the C# language designers, believe that ‘with’ often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.
For more information, see the Ask a C# Language Designer page.
[Author: Jon Skeet]
|
-
The choice between C# and VB.NET is largely one of subjective
preference. Some people like C#’s terse syntax, others like VB.NET’s
natural language, case-insensitive approach. Both have access to the same
framework libraries. Both will perform largely equivalently (with a few
small differences which are unlikely to affect most people, assuming
VB.NET is used with Option Strict on). Learning the .NET framework itself is
a much bigger issue than learning either of the languages, and it’s perfectly possible
to become fluent in both – so don’t worry too much about which to plump for. There are,
however, a few actual differences which may affect your decision:
VB.NET Advantages
- Support for optional parameters – very handy for some COM interoperability
- Support for late binding with
Option Strict off – type safety at compile time
goes out of the window, but legacy libraries which don’t have strongly typed interfaces
become easier to use.
- Support for named indexers (aka properties with parameters).
- Various legacy VB functions (provided in the
Microsoft.VisualBasic namespace, and can be
used by other languages with a reference to the Microsoft.VisualBasic.dll ). Many of
these can be harmful to performance if used unwisely, however, and many people believe they should
be avoided for the most part.
- The
with construct: it’s a matter of debate as to whether this is an advantage or not,
but it’s certainly a difference.
- Simpler (in expression – perhaps more complicated in understanding) event handling, where
a method can declare that it handles an event, rather than the handler having to be set up in code.
- The ability to implement interfaces with methods of different names. (Arguably this makes it harder
to find the implementation of an interface, however.)
Catch ... When ... clauses, which allow exceptions to be filtered based on runtime expressions
rather than just by type.
- The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an
advantage for small projects, people creating very large projects have found that the IDE slows down considerably
as the project gets larger.
C# Advantages
- XML documentation generated from source code comments. (This is coming in VB.NET with
Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code
already.)
- Operator overloading – again, coming to VB.NET in Whidbey.
- Language support for unsigned types (you can use them from VB.NET, but they aren’t in the language
itself). Again, support for these is coming to VB.NET in Whidbey.
- The
using statement, which makes unmanaged resource disposal simple.
- Explicit interface implementation, where an interface which is already implemented in a base class
can be reimplemented separately in a derived class. Arguably this makes the class harder to understand,
in the same way that member hiding normally does.
- Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations.
However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).
Note that unsafe code is still managed code, i.e. it is compiled to IL, JITted, and run within the CLR.
Despite the fact that the above list appears to favour VB.NET (if you don’t mind waiting for Whidbey),
many people prefer C#’s terse syntax enough to make them use C# instead.
[Author: Jon Skeet]
|
-
There are two versions of the C# specification – one from Microsoft, and one from ECMA. They are the same in all important respects (a few pieces of explanatory wording are different, but nothing that affects the specification itself) but the numbering of sections is different.
The ECMA specification is available as a PDF, or you can email ECMA and they will send you a hard copy for free. Details are on the ECMA website. Alternatively, Jon Jagger’s HTML version is available and is a useful download. It is from a draft version, but it’s very close to the final version. I don’t know whether or not Jon Jagger is planning to make an HTML copy of version 2 of the specification when it’s released.
The Microsoft version is available online or within the offline version of the MSDN – look for “specifications, Visual C#” in the index to find it quickly.
|
-
Section 10.9.2 of the language specification says:
A binary operator must take two parameters, at least one of which must have the class or struct type in which the operator is declared. Parameters of the shift operators (§7.8) are further constrained. A binary operator can return any type.
Why isn’t it limited to just returning bool?
There is some weirdness here because of the C# ability to support nullable types, such as the SQL types (ie SQLInt32, SQLSingle, etc.). These type can either have a value or be null.
One of the strange features of the SQL expression syntax is if either operand in a binary operation is null, the result is null. So, when we want to write the comparison operator for SQLInt32, we have a problem if the result type is constrained to bool, since null is neither true or false.
C# therefore allows the comparison operators to return another type as long as the resulting type has operator true and operator false defined. That gives us enough support to be able to write:
SQLInt32 x = …;
SQLInt32 y = …;
if (x == y)
{
// x and y or equal
}
else if (x != y)
{
// x and y are not equal
}
else
{
// the result of the comparison is null
}
Which allows the full richness of SQL types to be expressed.
Author: Eric Gunnerson]
|
|
|
|