473,405 Members | 2,279 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Attribute that is called by compiler during compilation?

I suspect it's unlikely, but you'll never know until you ask, but are there any attributes that would allow us to contribute to
the compiled output?

e.g.

// this class exists in a separate, compiled assembly for the compiler to load during compilation
class MyMethodCompiler : Attribute
{
// This is called during compilation
public override void GenerateMethod(MethodBuilder method)
{
// modify the IL that was generated from the compiler
}
}
// some class in a user assembly
class MyClass
{

[MyMethodCompiler]
public void SomeMethod(...)
{
// User code in method
...
...
...
}
}
May 4 '06 #1
5 2206
Alas no. This is not the goal of an attribute.

Code cannot be run at compile time because, well, the code hasn't been built
yet...

Attributes provide metadata which may be used at runtime but is only
available through reflection on a finished assembly or an instance of a
class. The Attribute based classes can have functional methods but are
usually "instantiated" by the process of reflection and an attribute cannot
alter the form of the code with which it is associated.

An attribute that has construction parameters will be created, instantiated,
when the TypeDescriptor.GetAttributes method is called. An attribute with no
constructor parameters will be instantiated at the moment that the
reflection process discovers an attribute of that type in the metadata. If
the attribute is way down on the list, the construction will take place
after the previous attributes have been created.

Once an attribute is instantiated by the process of reflection you can then
call its methods.

Find a little C# example after my signature...

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace StrangeAttribute

{

/// <summary>

/// Summary description for Form1.

/// </summary>

[

Pork(),

Pork("......Plonk")

]

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.Button button1;

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.Container components = null;

public Form1()

{

//

// Required for Windows Form Designer support

//

InitializeComponent();

//

// TODO: Add any constructor code after InitializeComponent call

//

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.button1 = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// button1

//

this.button1.Location = new System.Drawing.Point(96, 128);

this.button1.Name = "button1";

this.button1.TabIndex = 0;

this.button1.Text = "Reflect";

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// Form1

//

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

this.ClientSize = new System.Drawing.Size(292, 266);

this.Controls.Add(this.button1);

this.Name = "Form1";

this.Text = "Form1";

this.ResumeLayout(false);

}

#endregion

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void button1_Click(object sender, System.EventArgs e)

{

System.Diagnostics.Trace.WriteLine("Reflecting");

foreach(Attribute a in TypeDescriptor.GetAttributes(this,true))

{

System.Diagnostics.Trace.WriteLine("Got attribute: "+a.ToString());

if(a.GetType() == typeof(PorkAttribute))

{

((PorkAttribute)a).foo();

}

}

}

}

[

AttributeUsage(AttributeTargets.All, AllowMultiple=true)

]

public class PorkAttribute : Attribute

{

public PorkAttribute()

{

this.Arrgghh("!!");

}

public PorkAttribute(string stuff)

{

MessageBox.Show("This time it worked"+stuff);

}

void Arrgghh(string stuff)

{

MessageBox.Show("Attribute Constructed!!");

}

public void foo()

{

MessageBox.Show("Foo!!");

}

}

}

"Stuart Carnie" <st***********@nospam.nospam> wrote in message
news:OH**************@TK2MSFTNGP04.phx.gbl...
I suspect it's unlikely, but you'll never know until you ask, but are there
any attributes that would allow us to contribute to the compiled output?

e.g.

// this class exists in a separate, compiled assembly for the compiler to
load during compilation
class MyMethodCompiler : Attribute
{
// This is called during compilation
public override void GenerateMethod(MethodBuilder method)
{
// modify the IL that was generated from the compiler
}
}
// some class in a user assembly
class MyClass
{

[MyMethodCompiler]
public void SomeMethod(...)
{
// User code in method
...
...
...
}
}

May 4 '06 #2
What about the ConditionalAttribute - this does indeed affect compilation and resulting output.

Try the following code and use Lutz's Reflector - you will see CSC.exe was indeed influenced by the [Conditional] attribute.
There is no call to test.MethodTwo() in the resulting IL.

A condition would be the attribute would be compiled in a separate assembly, if it is going to be executed by the compiler, but
given my example below, certainly possible.

************************************

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyTest test = new MyTest();

test.MethodOne();
test.MethodTwo();
}

}

class MyTest
{
public void MethodOne()
{
Console.WriteLine("MethodOne");
}

[Conditional("NOCOMPILE")]
public void MethodTwo()
{
Console.WriteLine("MethodTwo");
}
}
}

************************************
Bob Powell [MVP] wrote:
Alas no. This is not the goal of an attribute.

Code cannot be run at compile time because, well, the code hasn't been built
yet...

Attributes provide metadata which may be used at runtime but is only
available through reflection on a finished assembly or an instance of a
class. The Attribute based classes can have functional methods but are
usually "instantiated" by the process of reflection and an attribute cannot
alter the form of the code with which it is associated.

An attribute that has construction parameters will be created, instantiated,
when the TypeDescriptor.GetAttributes method is called. An attribute with no
constructor parameters will be instantiated at the moment that the
reflection process discovers an attribute of that type in the metadata. If
the attribute is way down on the list, the construction will take place
after the previous attributes have been created.

Once an attribute is instantiated by the process of reflection you can then
call its methods.

Find a little C# example after my signature...

May 4 '06 #3
"certainly possible" suggests in a future version :) I it doesn't appear to be available today, but you never know what the
future holds.

Cheers,

Stu

Stuart Carnie wrote:
What about the ConditionalAttribute - this does indeed affect
compilation and resulting output.

Try the following code and use Lutz's Reflector - you will see CSC.exe
was indeed influenced by the [Conditional] attribute. There is no call
to test.MethodTwo() in the resulting IL.

A condition would be the attribute would be compiled in a separate
assembly, if it is going to be executed by the compiler, but given my
example below, certainly possible.

************************************

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyTest test = new MyTest();

test.MethodOne();
test.MethodTwo();
}

}

class MyTest
{
public void MethodOne()
{
Console.WriteLine("MethodOne");
}

[Conditional("NOCOMPILE")]
public void MethodTwo()
{
Console.WriteLine("MethodTwo");
}
}
}

************************************
Bob Powell [MVP] wrote:
Alas no. This is not the goal of an attribute.

Code cannot be run at compile time because, well, the code hasn't been
built yet...

Attributes provide metadata which may be used at runtime but is only
available through reflection on a finished assembly or an instance of
a class. The Attribute based classes can have functional methods but
are usually "instantiated" by the process of reflection and an
attribute cannot alter the form of the code with which it is associated.

An attribute that has construction parameters will be created,
instantiated, when the TypeDescriptor.GetAttributes method is called.
An attribute with no constructor parameters will be instantiated at
the moment that the reflection process discovers an attribute of that
type in the metadata. If the attribute is way down on the list, the
construction will take place after the previous attributes have been
created.

Once an attribute is instantiated by the process of reflection you can
then call its methods.

Find a little C# example after my signature...

May 4 '06 #4
Stuart,
A condition would be the attribute would be compiled in a separate assembly, if it is going to be executed by the compiler, but
given my example below, certainly possible.


But the ConditionalAttribute itself doesn't do anything here. It's
simply a hint to the compiler to possibly exclude calls to the method.
All the logic is in the compiler, the attribute is just a dumb class.

You could do the same today for your own attribute by extending one of
the open source C# compilers.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
May 4 '06 #5
Indeed - I'm suggesting a 'future' feature. An extensible compiler. How useful would that be!

Mattias Sjögren wrote:
Stuart,
A condition would be the attribute would be compiled in a separate assembly, if it is going to be executed by the compiler, but
given my example below, certainly possible.


But the ConditionalAttribute itself doesn't do anything here. It's
simply a hint to the compiler to possibly exclude calls to the method.
All the logic is in the compiler, the attribute is just a dumb class.

You could do the same today for your own attribute by extending one of
the open source C# compilers.
Mattias

May 5 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: K. Shier | last post by:
when attempting to edit code in a class file, i see the bug "Visual Basic ..NET compiler is unable to recover from the following error: System Error &Hc0000005&(Visual Basic internal compiler...
2
by: Mike Fisher | last post by:
I'm seeing an error when I try to run/debug a web service. Although it doesn't happen every time, it does occur more than half of the times I hit F5. It appears to be returned by the the JIT...
4
by: Julia | last post by:
Hi, Is there any why I could use attribute or something else to instruct the compiler to inject a specific code for a property? for example i have the following property and i would like that...
1
by: Skip | last post by:
Hi, I created a COM object in C# and everything works fine on my machine. Now, the compiler gives me the following messages when compiling my code: ------ Rebuild All started: Project: SI,...
1
by: Invalidlastname | last post by:
Hi, Our developer team recently started getting the compilation error, see below, once a while running the asp.net web application from Visual Studio 2003 (in debug mode), and we have to rebuild the...
9
by: JTrigger | last post by:
When I compile my project using the IDE on a development machine it works just fine. When I compile it on the server using csc.exe, I get the following error when I try to bring it up in the web...
1
by: christian.Blackburn | last post by:
Hi Gang, On my development system I am not getting this error, but it does happen when I upload it to my ISP. Can someone tell me why this is happening? I don't have any user-defined controls...
1
by: Marek | last post by:
I use VS2005 with framework 2.0 and I just found a behavior I consider odd. Here is the code that illustrates th eproblem: public static void MethodA() { MethodB() } #if DEBUG
3
by: dancer | last post by:
I am using Framework 1.1.4322. Who can tell me why I'm getting this error? My code follows Compilation Error Description: An error occurred during the compilation of a resource required to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.