tags:

views:

2309

answers:

16

All code written in .NET languages compiles to MSIL, but are there specific tasks / operations that you can do only using MSIL directly?

Let us also have things done easier in MSIL than C#, VB.NET, F#, j# or any other .NET language.

So far we have this:
1. Tail recursion
2. Generic Co/Contravariance
3. Overloads which differ only in return types
4. Override access modifiers
5. Have a class which cannot inherit from System.Object
6. Filtered exceptions (can be done in vb.net)
7. Calling a virtual method of the current static class type.
8. Get a handle on the boxed version of a value type.
9. Do a try/fault.
10. Usage of forbidden names.
11. Define your own parameterless constructors for value types.
12. Define events with a raise element.
13. Some conversions allowed by the CLR but not by C#.
14. Make a non main() method as the .entrypoint.
15. work with the native int and native unsigned int types directly.
16. Play with transient pointers
17. emitbyte directive in MethodBodyItem
18. Throw and catch non System.Exception types
19. Inherit Enums (Unverified)
20. You can treat an array of bytes as a (4x smaller) array of ints.
21. You can have a field/method/property/event all have the same name(Unverified).

+14  A: 

The CLR supports generic co/contravariance already, but C# is not getting this feature until 4.0

ermau
Can you provide a link with more info on this?
Binoj Antony
+14  A: 

MSIL allows for overloads which differ only in return types because of

call void [mscorlib]System.Console::Write(string)

or

callvirt int32 ...
Anton Gogolev
How do you know this kind of stuff? :)
Gerrie Schenck
http://msmvps.com/blogs/luisabreu/archive/2007/09/06/c-overloading-methods-by-return-type-is-not-permitted.aspx
Anton Gogolev
This is awesome. Who hasn't wanted to make return overloads?
Jimmy Hoffa
+16  A: 

Most .Net languages including C# and VB do not use the tail recursion feature of MSIL code.

Tail recursion is an optimization that is common in functional languages. It occurs when a method A ends by returning the value of method B such that method A's stack can be deallocated once the call to method B is made.

MSIL code supports tail recursion explicitly, and for some algorithms this could be a important optimization to make. But since C# and VB do not generate the instructions to do this, it must be done manually (or using F# or some other language).

Jeffrey L Whitledge
F# does not use MSIL's tail recursion, because it only works in fully trusted (CAS) cases because of the way it does not leave a stack to check for permission assrtions (etc.).
Richard
Richard, I'm not sure what you mean. F# certainly does emit the tail. call prefix, pretty much all over the place. Examine the IL for this: "let print x = print_any x".
MichaelGG
I believe that the JIT will use tail recursion anyway in some cases - and in some cases will ignore the explicit request for it. It depends on the processor architecture, IIRC.
Jon Skeet
@Jon Skeet, processor architecture is irrelevant for implementing tail recursion (I.e., processor-agnostic languages like Eiffel is known to optimize code this way, as does Saxon's XSLT2-SA, with Java byte code). But yes, a JIT could be optimized to do so, regardless of processor, and it does happen with .NET's JIT.
Abel
@Abel: While processor architecture is irrelevant in *theory*, it's not irrelevant in *practice* as the different JITs for different architectures have different rules for tail recursion in .NET. In other words, you could *very easily* have a program which blew up on x86 but not on x64. Just because tail recursion *can* be implemented in both cases doesn't mean it *is*. Note that this question is about .NET specifically.
Jon Skeet
@Jon Skeet, yes, this way it makes sense. Sorry for misunderstanding you earlier. You never sleep, do you? ;)
Abel
+12  A: 

In MSIL, you can have a class which cannot inherit from System.Object.

Sample code: compile it with ilasm.exe UPDATE: You must use "/NOAUTOINHERIT" to prevent assembler from auto inheriting.

// Metadata version: v2.0.50215
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 2:0:0:0
}
.assembly sample
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .hash algorithm 0x00008004
  .ver 0:0:0:0
}
.module sample.exe
// MVID: {A224F460-A049-4A03-9E71-80A36DBBBCD3}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00000001    //  ILONLY
// Image base: 0x02F20000


// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit Hello
{
  .method public hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Hello World!"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Hello::Main
} // end of class Hello
Ramesh
Any link to validate this?
Binoj Antony
#Binok-Antony : I have added sample code, which can be compiled using ilasm.exe and can be executed.
Ramesh
That doesn't *explicitly* inherit from System.Object, but it does it implicitly, I believe. See ECMA 335 section 8.9.9 - it has to *at least* indirectly inherit from System.Object.
Jon Skeet
If you compile, and then disassemble, you'll see: .class public auto ansi beforefieldinit Hello extends [mscorlib]System.Object
Michael Trausch
@www.trausch.us - you need to compile using ilasm code.il /NOAUTOINHERIT
Ramesh
@Ramesh That is non-portable; that option does not exist in (for example) the Mono 2.0 version of ilasm which follows ECMA as cited by Jon Skeet strictly.
Michael Trausch
@Jon Skeet - With all due respect, Could you please help me understand what NOAUTOINHERIT mean. MSDN specifies "Disables default inheritance from Object when no base class is specified.New in the .NET Framework version 2.0."
Ramesh
@Michael - The question is regarding MSIL and not Common Intermediate Language. I agree this may not be possible in CIL but, it still works with MSIL
Ramesh
@Ramesh: Oops, you're absolutely right. I'd say at that point it breaks the standard spec, and shouldn't be used. Reflector doesn't even load the assmebly. However, it *can* be done with ilasm. I wonder why on earth it's there.
Jon Skeet
(Ah, I see the /noautoinherit bit was added after my comment. At least I feel somewhat better about not realising it before...)
Jon Skeet
@Jon - Yes I added after seeing, Michael comment. I would modify the answer to reflect I have updated it.
Ramesh
@Ramesh: Sorry, I wasn't trying to criticise you for not making the update more obviously an update earlier on. I was just relieved that I hadn't missed anything glaringly obvious or failed to read your question the first time. I still wonder what the point is though...
Jon Skeet
@Ramesh / @Jon Skeet / @all: FWIW the line in Ecma-335 that defines and prohibits this is: *"Every Class (with the exception of `System.Object` and the special class `<Module>`) shall extend one, and only one, other Class – so `Extends` for a Class shall be non-null [ERROR]"* (the word error here means: if this rule is not obeyed, an error must be raised). I think that pretty much sums it up *why* this cannot work.
Abel
+4  A: 

With IL and VB.NET you can add filters when catching exceptions, but C# v3 does not support this feature.

This VB.Net example is taken from http://blogs.msdn.com/clrteam/archive/2009/02/05/catch-rethrow-and-filters-why-you-should-care.aspx (note the When ShouldCatch(ex) = True in the Catch clause):

Try
   Foo()
Catch ex As CustomBaseException When ShouldCatch(ex) = True
   Console.WriteLine("Caught exception!")
End Try
Emanuele Aina
Please rRemove the `= True`, it's making my eyes bleed!
Konrad Rudolph
Why? This is VB and not C#, so no =/== problems exist. ;-)
peSHIr
Well c# can do "throw;", so the same result can be achieved.
Frank Schwieterman
paSHIr, I believe he was talking about the redudancy of it
+12  A: 

It's possible to combine the protected and internal access modifiers. In C#, if you write protected internal a member is accessible from the assembly and from derived classes. Via MSIL you can get a member which is accessible from derived classes within the assembly only. (I think that could be pretty useful!)

yatima2975
+5  A: 

IL has the distinction between call and callvirt for virtual method calls. By using the former you can force calling a virtual method of the current static class type instead of the virtual function in the dynamic class type.

C# has no way of doing this:

abstract class Foo {
    public void F() {
        Console.WriteLine(ToString()); // Always a virtual call!
    }

    public override string ToString() { System.Diagnostics.Debug.Assert(false); }
};

sealed class Bar : Foo {
    public override string ToString() { return "I'm called!"; }
}

VB, like IL, can issue nonvirtual calls by using the MyClass.Method() syntax. In the above, this would be MyClass.ToString().

Konrad Rudolph
+11  A: 

Ooh, I didn't spot this at the time. (If you add the jon-skeet tag it's more likely, but I don't check it that often.)

It looks like you've got pretty good answers already. In addition:

  • You can't get a handle on the boxed version of a value type in C#. You can in C++/CLI
  • You can't do a try/fault in C# ("fault" is a like a "catch everything and rethrow at the end of the block" or "finally but only on failure")
  • There are lots of names which are forbidden by C# but legal IL
  • IL allows you to define your own parameterless constructors for value types.
  • You can't define events with a "raise" element in C#. (In VB you have to for custom events, but "default" events don't include one.)
  • Some conversions are allowed by the CLR but not by C#. If you go via object in C#, these will sometimes work. See a uint[]/int[] SO question for an example.

I'll add to this if I think of anything else...

Jon Skeet
Ah the jon-skeet tag, I knew I was missing something!
Binoj Antony
To use illegal identifier name you can prefix it with @ in C#
George Polevoy
@George: That works for keywords, but not all valid IL names. Try specifying `<>a` as a name in C#...
Jon Skeet
+4  A: 

Native types
You can work with the native int and native unsigned int types directly (in c# you can only work on an IntPtr which is not the same.

Transient Pointers
You can play with transient pointers, which are pointers to managed types but guaranteed not to move in memory since they are not in the managed heap. Not entirely sure how you could usefully use this without messing with unmanaged code but it's not exposed to the other languages directly only through things like stackalloc.

<Module>
you can mess about with the class if you so desire (you can do this by reflection without needing IL)

.emitbyte

15.4.1.1 The .emitbyte directive MethodBodyItem ::= … | .emitbyte Int32 This directive causes an unsigned 8-bit value to be emitted directly into the CIL stream of the method, at the point at which the directive appears. [Note: The .emitbyte directive is used for generating tests. It is not required in generating regular programs. end note]

.entrypoint
You have a bit more flexibility on this, you can apply it to methods not called Main for example.

have a read of the spec I'm sure you'll find a few more.

ShuggyCoUk
+1, some hidden gems here. Note that `<Module>` is meant as special class for languages that accept global methods (like VB does), but indeed, C# cannot access it directly.
Abel
+2  A: 

I think the one I kept wishing for (with entirely the wrong reasons) was inheritance in Enums. It doesn't seem like a hard thing to do in SMIL (since Enums are just classes) but it's not something the C# syntax wants you to do.

scraimer
+9  A: 

In IL you can throw and catch any type at all, not just types derived from System.Exception.

Daniel Earwicker
You can do that in C# too, with `try`/`catch` without parentheses in the catch-statement you will catch non-Exception-like exceptions too. Throwing, however, is indeed only possible when you inherit from `Exception`.
Abel
+3  A: 

Here's some more:

  1. You can have extra instance methods in delegates.
  2. Delegates can implement interfaces.
  3. You can have static members in delegates and interfaces.
leppie
+2  A: 

20) You can treat an array of bytes as a (4x smaller) array of ints.

I used this recently to do a fast XOR implementation, since the CLR xor function operates on ints and I needed to do XOR on a byte stream.

The resulting code measured to be ~10x faster than the equivalent done in C# (doing XOR on each byte).

===

I don't have enough stackoverflow street credz to edit the question and add this to the list as #20, if someone else could that would be swell ;-)

rosenfield
Rather than dip into IL, you could have accomplished this with unsafe pointers. I'd imagine it would have been just as fast, and perhaps faster, since it would do no bounds checking.
P Daddy
+2  A: 

Something obfuscators use - you can have a field/method/property/event all have the same name.

Jason Haley
any references to this?
Binoj Antony
I put a sample out on my site: http://jasonhaley.com/files/NameTestA.zipIn that zip there is the IL and an exe that contains a class with the following all the same 'A':-class name is A-Event named A-Method named A-Property named A-2 Fields named AI can't find a good reference to point you at, though I probably read it in either the ecma 335 spec or Serge Lidin's book.
Jason Haley
+4  A: 

As far as I know, there's no way to make module initializers (static constructors for an entire module) directly in C#:

http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx

yoyoyoyosef
+1 spot on! A great miss in C#, as [I noticed here](http://stackoverflow.com/questions/3363569/what-is-the-earliest-entrypoint-that-the-clr-calls-before-calling-any-method-in-a/3363783#3363783).
Abel
+1  A: 

You can hack method override co/contra-variance, which C# doesn't allow (this is NOT the same as generic variance!). I've got more information on implementing this here, and parts 1 and 2

thecoop
+1 Excellent hacking!
Jordão