2

I want to create my custom statements for the c# compiler to generate a try finally block. Just like the lock statement.

Forexample

private readonly ReaderWriterLockSlim _lockObject

private void MyMethod()
{
   MyWriteLock(lockObject)
   {

   }
}

private void MyMethod2()
{
   MyReadLock(lockObject)
   {

   }
}

Compiler should generate following code for me

private void MyMethod()
{
   try
   {
     lockObject.EnterWriteLock();
     .. statetments for the method    
   }
   finally 
   {
     _lockObject.ExitWriteLock();
   }
}

private void MyMethod2()
{
   try
   {
     lockObject.EnterReadLock();
     .. statetments for the method    
   }
   finally 
   {
     _lockObject.ExitReadLock();
   }
}
aeje
  • 239
  • 1
  • 9
  • 3
    what about code snippets? See [Creating and Using IntelliSense Code Snippets](http://msdn.microsoft.com/en-us/library/ms165392(v=VS.100).aspx) – sll Dec 22 '11 at 09:08

3 Answers3

6

You can't create your own statements in C#. The closest you can come for try/finally is a using statement:

using (lockObject.AcquireReadToken())
{
}

where AcquireReadToken() would acquire a read lock, and return an IDisposable which releases the lock when it's disposed.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You should give a try to ILWeaving. I haven't tried that, but a lot of 'magic' can be done using ILWeaving. I use NotifyPropertyWeaver which uses ILWeaving to inject code.

NotifyPropertyWeaver

Refer this question

What is IL Weaving?

Community
  • 1
  • 1
P.K
  • 18,587
  • 11
  • 45
  • 51
0

You could do this with ILWeaving using one of the following

However I think in this case making use of a 'using' statement as suggested by @JonSkeet would be the much simpler solution.

That is, of course, unless you are interested in learning about IL Manipulation. In which case go for it :)

Simon
  • 33,714
  • 21
  • 133
  • 202