FAQ Suggestions

R

Richard A. Lowe

Hi, here are answers for some of the questions I suggested a short time ago
for the m.p.d.l.c FAQ Jon Skeet is organizing. It was Jon's intention that
these be 'honed' by the group before being included - so hone away. It's my
intention that you merely not 'tear me a new one' for any inaccuracies in my
answers. I give credit to Anders Hejlsberg for answering my question about
the non-int operators a short while ago in this thread (which is the basis
for my answer below):
http://www.gotdotnet.com/Community/MessageBoard/Thread.aspx?id=157575

- what's the difference between using cast syntax and the 'as' operator? (C#
as a language)

Using the 'as' operator differs from a cast in C# in three important ways:
1. It returns a null when the variable you are trying to convert is not of
the requested type or in it's inheritance chain
2. It can only be applied to reference type variables converting to
reference types.
3. 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).

- how do I use an alias for a namespace or class? (C# as a language)

Use the 'using' directive to create an alias for a long namespace or class.
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.
// namespace:
using act = System.Runtime.Remoting.Activation;
// class
using list = System.Collections.ArrayList;

- why doesn't C# have checked exceptions? (C# as a language??)

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:
http://www.artima.com/intv/handcuffs.html
http://www.mindview.net/Etc/Discussions/CheckedExceptions

- why are struct constructors in C# required to have at least one argument?
(C# as a language)

The .NET runtime can't guarantee that parameterless constructors will be
called. If structs where to allow default, parameterless constructors, it
would imply that these default constructors would *always* be called.
However, the runtime can not make this guarantee. For example an array of
value types will be initialized to the initial values of it's members (i.e.
0 for number type primitive members, null for reference types etc) *NOT to
the values provided in a default constructor* - which makes structs better
performing by not having to call constructor code. Enforcing a minimum of
one parameter in the constructor reduces the possibility that someone will
define a constructor that they then expect to be called every time one of
their struct types is constructed.

- how can I show an int as a binary number - a string of 1's and 0's

The convert class has an overload of the static ToString() method that takes
two ints and returns a string populated with the number in the specified
base.
Convert.ToString(128, 2);

- why does C# return an int when you add two bytes/shorts/sbytes/ushorts
together?

C# always promotes 8 and 16 bit values to 32 bits before performing
arithmetic operations. It is actually less efficient to emulate 8 or 16 bit
arithmetic on a 32 bit processor than it is to just do the operations in 32
bits.

C# narrowing conversions (conversions that might affect the magnitude of a
number like casting an int to short) are always explicit. By contrast they
can occur implicitly in C/C++. That's why you have to cast the result of
expressions like ushort + ushort back to ushort in an assignment.

- how can I speed up P/Invoke calls made through C# to external functions?

One easy way is to apply the SuppressUnmanagedCodeSecurityAttribute to the
method, class or interface that you are making platform invoke calls
through. Apply this attribute bypasses the runtime security check that
ensures that the code calling the external method has UnmanagedCode
permission. This can cause a serious security violation in your application
and using it means that securing this unmanaged call is the responsibility
of the developer, not the framework.

example:
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("User32.dll")]
public extern static int GetCursorPos( ref Point thePoint );

- why doesn't calling Initialize() on a reference-type array fill in the
array with objects?

The System.Array class instance method Initialize() exists solely to
initialize value type arrays to their default values and is not valid on
reference type arrays. (In fact it is not even intended for C# value type
structs, as these structs can have no default constructor for Initialize to
call.)

- How can I implement a *global* hook in C#?

It is not possible because C# / .NET does not support an essential element:
a DLL export providing a consistent function pointer. See here
http://support.microsoft.com/?kbid=318804 at the bottom for a little more
detail.

- How do I tell C# what kind of literal number I want? (f, L, U etc) (C# as

If you need to tell C# that you want it to treat a literal as a particular
type of number, you may do so by adding a number type suffix at the end of
the literal you provide:

1U; // an unsiged int
1ul; // an unsigned long
1f; // a System.Single floating-point number;

This is somewhat important because sometimes you must match a literal to the
signature of something or specify the value to 'defeat' an implicit cast
behavior you don't like. For example this:
Hashtable names = new Hashtable(100, 0.1);
won't compile because it takes the signatures (int, float) and the above is
(int, double). The line should read:
Hashtable names = new Hashtable(100, 0.1f);

A full listing of the suffixes is in the Grammar portion of the c#
specification under C.1.8 Literals.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_C.asp

- What's the difference between the ref and out modifiers on parameters?

Both the ref and out method parameters are applied to arguments of a method
and both mean that the argument will be passed "by reference" (either a
value type variable by reference or a reference type variable by reference).
The out parameter, however, allows you to pass in an uninitialized variable
like so and guarantees it will come back with it's value set (so long as the
called method was written in C#, anyway).

int i;
DoStuffByRef(out i);
// i is now a usable int value
 
J

Jon Skeet [C# MVP]

Richard A. Lowe said:
Hi, here are answers for some of the questions I suggested a short time ago
for the m.p.d.l.c FAQ Jon Skeet is organizing. It was Jon's intention that
these be 'honed' by the group before being included - so hone away. It's my
intention that you merely not 'tear me a new one' for any inaccuracies in my
answers. I give credit to Anders Hejlsberg for answering my question about
the non-int operators a short while ago in this thread (which is the basis
for my answer below):

Great stuff - thanks very much for all your work! A few comments (with
questions without any comments snipped).
- why are struct constructors in C# required to have at least one argument?
(C# as a language)

The .NET runtime can't guarantee that parameterless constructors will be
called. If structs where to allow default, parameterless constructors, it
would imply that these default constructors would *always* be called.

I'm going to try to steer clear of using "default" for parameters
unless I'm talking about the constructor supplied by default if you
don't give one (in a reference type). I believe "parameterless" is
actually the correct term - for instance, you can't supply a default
constructor for a reference type, you just get given one if you don't
supply any constructors at all. This is one piece of terminology which
is much abused (including by Microsoft), but I believe the difference
can be useful, so I'll try to draw a distinction.

On the other hand, I've just looked at the CLR spec and that mentions
default constructors 3 times, so maybe I'm just wrong. Shame though, I
thought it was quite handy...
However, the runtime can not make this guarantee. For example an array of
value types will be initialized to the initial values of it's members (i.e.
0 for number type primitive members, null for reference types etc) *NOT to
the values provided in a default constructor* - which makes structs better
performing by not having to call constructor code. Enforcing a minimum of
one parameter in the constructor reduces the possibility that someone will
define a constructor that they then expect to be called every time one of
their struct types is constructed.

Explaining here that CLR types *can* have parameterless constructors,
but C# can't generate such types would be a good idea. It took me a
while to work out what was meant here.
- why does C# return an int when you add two bytes/shorts/sbytes/ushorts
together?

C# always promotes 8 and 16 bit values to 32 bits before performing
arithmetic operations. It is actually less efficient to emulate 8 or 16 bit
arithmetic on a 32 bit processor than it is to just do the operations in 32
bits.

C# narrowing conversions (conversions that might affect the magnitude of a
number like casting an int to short) are always explicit. By contrast they
can occur implicitly in C/C++. That's why you have to cast the result of
expressions like ushort + ushort back to ushort in an assignment.

I would personally stick to short in the example here, just so people
don't think it's got *anything* to do with being unsigned!
- How can I implement a *global* hook in C#?

It is not possible because C# / .NET does not support an essential element:
a DLL export providing a consistent function pointer. See here
http://support.microsoft.com/?kbid=318804 at the bottom for a little more
detail.

It might be worth making the question a bit more explicit in terms of
what a global hook is, just for clarity. (Or put it in the answer.)
- How do I tell C# what kind of literal number I want? (f, L, U etc) (C# as

If you need to tell C# that you want it to treat a literal as a particular
type of number, you may do so by adding a number type suffix at the end of
the literal you provide:

1U; // an unsiged int
1ul; // an unsigned long
1f; // a System.Single floating-point number;

Add
1d // a System.Double floating-point number
1m // a System.Decimal floating-point number

Then at least even if there aren't all the variants in terms of case,
all the bases are covered, as it were.
This is somewhat important because sometimes you must match a literal to the
signature of something or specify the value to 'defeat' an implicit cast
behavior you don't like. For example this:
Hashtable names = new Hashtable(100, 0.1);
won't compile because it takes the signatures (int, float) and the above is
(int, double). The line should read:
Hashtable names = new Hashtable(100, 0.1f);

A full listing of the suffixes is in the Grammar portion of the c#
specification under C.1.8 Literals.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspe
c/html/vclrfcsharpspec_C.asp

Unless anyone particularly minds, I'd like to keep to the ECMA spec
rather than the MS spec for references. This may be impossible for 2.0
features for a while, but the FAQ can be fixed later for those features
:)
- What's the difference between the ref and out modifiers on parameters?

Both the ref and out method parameters are applied to arguments of a method
and both mean that the argument will be passed "by reference" (either a
value type variable by reference or a reference type variable by reference).
The out parameter, however, allows you to pass in an uninitialized variable
like so and guarantees it will come back with it's value set (so long as the
called method was written in C#, anyway).

int i;
DoStuffByRef(out i);
// i is now a usable int value

Gosh, I'm surprised I don't have that in there already. I'll include a
link to my page about parameter passing...
 
D

Daniel O'Connell [C# MVP]

Jon Skeet said:
It might be worth making the question a bit more explicit in terms of
what a global hook is, just for clarity. (Or put it in the answer.)

Perhaps a more general "Why doesn't C# allow exporting functions in dlls",
especially considering that it is possible in IL(If memory serves, don't
recall how to do it). I can find the answer, just don't want to dig through
Brumme's blogs right now.

Anyway, after explaining why you can't export functions, it would be easy to
explain why xprocs, global hooks, and other such things aren't possible with
C#.
Add
1d // a System.Double floating-point number
1m // a System.Decimal floating-point number

Then at least even if there aren't all the variants in terms of case,
all the bases are covered, as it were.


Unless anyone particularly minds, I'd like to keep to the ECMA spec
rather than the MS spec for references. This may be impossible for 2.0
features for a while, but the FAQ can be fixed later for those features
:)

I agree on this, ECMA spec is prefereable. ALthough,is the MS spec just a
clone or is it a rewrite?(I've never actually used the msdn spec).
 
M

Mattias Sjögren

Richard,
- why does C# return an int when you add two bytes/shorts/sbytes/ushorts
together?

C# always promotes 8 and 16 bit values to 32 bits before performing
arithmetic operations. It is actually less efficient to emulate 8 or 16 bit
arithmetic on a 32 bit processor than it is to just do the operations in 32
bits.

C# narrowing conversions (conversions that might affect the magnitude of a
number like casting an int to short) are always explicit. By contrast they
can occur implicitly in C/C++. That's why you have to cast the result of
expressions like ushort + ushort back to ushort in an assignment.


Here I think it's worth pointing out the special case for compound
assignment operators (14.13.2).

- how can I speed up P/Invoke calls made through C# to external functions?

One easy way is to apply the SuppressUnmanagedCodeSecurityAttribute to the
method, class or interface that you are making platform invoke calls
through. Apply this attribute bypasses the runtime security check that
ensures that the code calling the external method has UnmanagedCode
permission. This can cause a serious security violation in your application
and using it means that securing this unmanaged call is the responsibility
of the developer, not the framework.

Well SUCSA is only one way to speed up interop code (and probably the
last one I'd recommend people to use, because of the security stuff).
I think it's more important to promote correct use of In/Out
attributes and parameter typing to avoid unnecessary marshaling, and
making "chunky" rather than "chatty" calls if possible.

- How can I implement a *global* hook in C#?
It is not possible because C# / .NET does not support an essential element:
a DLL export providing a consistent function pointer.

C# doesn't support it, but C++ and IL Assembler does. But getting a
function export is only part of the problem. It would be a terrible
idea to force the CLR to be loaded into every process the hook code is
run in anyway.



Mattias
 
J

Jon Skeet [C# MVP]

[Using the ECMA spec]
I agree on this, ECMA spec is prefereable. ALthough,is the MS spec just a
clone or is it a rewrite?(I've never actually used the msdn spec).

I believe they're *almost* word-for-word identical, but with different
examples in some places and (more importantly) different numbering.
 
R

Richard A. Lowe

Inline

--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
Mattias Sjögren said:
Richard,



Here I think it's worth pointing out the special case for compound
assignment operators (14.13.2).

Okay, I will add that.
Well SUCSA is only one way to speed up interop code (and probably the
last one I'd recommend people to use, because of the security stuff).
I think it's more important to promote correct use of In/Out
attributes and parameter typing to avoid unnecessary marshaling, and
making "chunky" rather than "chatty" calls if possible.

I know of no one more qualified than you to write such a thing, Mattias, if
you want to take a stab at it. Otherwise be happy to I'll give it a try.
 
N

Nick Malik

Hello Jon and Richard,

I wasn't aware of your effort.

Have you thought of allowing your FAQs to be compiled on a Wiki server?

In my mind, the advantage would be that the FAQs can be honed by the
community (or the MVP) on an ongoing basis, not just a one-off effort.

Either way, it's a valuable effort. Thanks for doing this work.

--- Nick
 
J

Jon Skeet [C# MVP]

Nick Malik said:
I wasn't aware of your effort.

Have you thought of allowing your FAQs to be compiled on a Wiki server?

In my mind, the advantage would be that the FAQs can be honed by the
community (or the MVP) on an ongoing basis, not just a one-off effort.

Either way, it's a valuable effort. Thanks for doing this work.

I considered using a Wiki, but in my experience they can end up being
hard to read due to conversation, and harder to keep consistent.

As it is, I'm suggesting that discussion about FAQ answers should occur
on the newsgroup, and I'll keep it up to date with that (once
conversation has settled down on any particular point). I'm also
currently adding extra questions/answers autonomously occasionally,
which will hopefully stop in a month or so.

It's certainly not going to be a one-off effort - merely a more
co-ordinated one than might happen with a Wiki :)
 
D

Daniel O'Connell [C# MVP]

Daniel O'Connell said:
Perhaps a more general "Why doesn't C# allow exporting functions in dlls",
especially considering that it is possible in IL(If memory serves, don't
recall how to do it). I can find the answer, just don't want to dig
through Brumme's blogs right now.

Found the blog I was referencing[1].

The basic reasons are how such calls enter the assembly, specifically which
app domain. The current mechanisms are not paticularly desirable and may be
confusing at best.



1. http://blogs.msdn.com/cbrumme/archive/2003/04/15/51325.aspx
Anyway, after explaining why you can't export functions, it would be easy
to explain why xprocs, global hooks, and other such things aren't possible
with C#.
Add
1d // a System.Double floating-point number
1m // a System.Decimal floating-point number

Then at least even if there aren't all the variants in terms of case,
all the bases are covered, as it were.


Unless anyone particularly minds, I'd like to keep to the ECMA spec
rather than the MS spec for references. This may be impossible for 2.0
features for a while, but the FAQ can be fixed later for those features
:)

I agree on this, ECMA spec is prefereable. ALthough,is the MS spec just a
clone or is it a rewrite?(I've never actually used the msdn spec).
 
J

Jon Skeet [C# MVP]

<snip>

I've now added these questions (and answers):
- what's the difference between using cast syntax and the 'as' operator?
- how do I use an alias for a namespace or class?
- why doesn't C# have checked exceptions?
- why are struct constructors in C# required to have at least one argument?
- how can I show an int as a binary number - a string of 1's and 0's
- why doesn't calling Initialize() on a reference-type array fill in the
array with objects?
- How do I tell C# what kind of literal number I want? (f, L, U etc) (C# as
- What's the difference between the ref and out modifiers on parameters?

I haven't added these questions, as I believe more detailed answers are
pending:
 
S

Sam Gentile [MVP - C#/.NET]

While this is a great first step, I would like to see something where this
has teeth - in other words when that "do you need the framework installed to
run that .NET app" comes up for the dozen time that day, that we all have a
consistent approach in directing people to the FAQ.

--
--------------------------------------------------------------
Sam Gentile [C#/.NET MVP]
..NET Blog http://samgentile.com/blog/
MSDN Column:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/bridge.asp
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
 
J

Joe Mayo [C# MVP]

Sam Gentile said:
While this is a great first step, I would like to see something where this
has teeth - in other words when that "do you need the framework installed to
run that .NET app" comes up for the dozen time that day, that we all have a
consistent approach in directing people to the FAQ.


Hi Sam,

I totally agree. The way Jon has published it we can drill down on a FAQ
and easily post the URL to the exact answer.

Joe
 
R

Richard A. Lowe

Yes, also for theargument?
but I'll just submit that for an update.

Sorry for the delay - it's been a hectic couple of weeks...
Richard
 
J

Jon Skeet [C# MVP]

Richard A. Lowe said:
Yes, also for the
argument?
but I'll just submit that for an update.

Sorry for the delay - it's been a hectic couple of weeks...

No rush - after all it took me about 6 months to get the first version
out of the door!
 
J

Jon Skeet [C# MVP]


I'd love to see that too - but it's certainly *starting*. Every so
often I'll see a question and be just ready to post a FAQ answer, only
to see that someone's got there already :)
I totally agree. The way Jon has published it we can drill down on a FAQ
and easily post the URL to the exact answer.

Yes - although I have concerns about the way I've done it, now. The FAQ
is already getting pretty large, and I can only see it getting larger.
I wonder whether I shouldn't have split it into more pages to start
with, or given some what of posting a URL which would redirect to the
appropriate place in a way which gives more flexibility.

I'm still thinking on that (a simple servlet which knew how to redirect
appropriately would do, along with some easy way of getting the right
URL to post) but I'd welcome any ideas - including "it's fine the way
it is".
 
J

Joe Mayo [C# MVP]

Jon Skeet said:
Yes - although I have concerns about the way I've done it, now. The FAQ
is already getting pretty large, and I can only see it getting larger.
I wonder whether I shouldn't have split it into more pages to start
with, or given some what of posting a URL which would redirect to the
appropriate place in a way which gives more flexibility.

I'm still thinking on that (a simple servlet which knew how to redirect
appropriately would do, along with some easy way of getting the right
URL to post) but I'd welcome any ideas - including "it's fine the way
it is".


I like the way the Windows Forms FAQ on SyncFusion is done. It is really
easy to find things, navigate, and reference.

Joe
 
J

Jon Skeet [C# MVP]

Joe Mayo said:
I like the way the Windows Forms FAQ on SyncFusion is done. It is really
easy to find things, navigate, and reference.

Right. (The first page is still huge for that, but only because there
are *so* many questions.) I'll look at the options for changing the
format. The downside is that existing references will become invalid,
but I could have a transitional period...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top