I am reading the Andrew Troelsen's book "Pro C# 2008 and the .Net 3.5 platform" bit un-regularly. I am finding this book bit interesting as it covers the chapters in a naive way. I came across two new features (Partial Methods and Automatic properties) in .Net 3.5 which are not complex to understand. But there are some constraints in using these features which Andrew left us to think through by ourselves. I thought through them and compiled my understanding as below. This blog will have about the Partial methods and will write on Automatic properties in a day.
Partial Methods - allows only void return type
Partial methods allow us to write the method implementation in a different class (partial class) by keeping just the method definition in a partial class. This feature though has few constraints which you will get to know by reading the above book. One of the constraint is that partial methods allow only void return type. Why is that?
Possibly, because until the partial method is implemented, your disassembled code will not show up the partial method definition. To explain further, please follow the example.
For ex :
namespace MyDotNet35
{
public partial class TestHarness
{
public bool myTestMethod()
{
.....do something ....
myPartialMethod() ; //call the partial method
....do something ....
}
partial void myPartialMethod();
}
}
If you look at the compiled IL of the above class, you will not get to see the myPartialMethod() call inside the myTestMethod until it is implemented in another partial class as below.
namespace MyDotNet35
{
public partial class TestHarness
{
partial void myPartialMethod()
{
//actual implementation of the partial method is here.
}
}
}
If my partial method returns an integer, then its possible for me to write the code above as
namespace MyDotNet35
{
public partial class TestHarness
{
public bool myTestMethod()
{
.....do something ....
int retVal = myPartialMethod() ; //call the partial method
if (retVal == someValue){
....do something ....
}
}
partial void myPartialMethod();
}
}
Imagine what would be the compiled version of IL....?
Yes, the compiler cannot leave the myPartialMethod call in this case (though the implementation is not done yet) as it is required to store the output to a variable and also some validation takes place based on the return value of the partial method.
Now, that's why the partial methods should have only void return type....got it.
Wednesday, March 25, 2009
Subscribe to:
Post Comments (Atom)
1 comment:
There is alternative way of implementing.
Refer code snippet below:
// Read only
public int age
{
get;
private set;
}
// Write only
public String Address
{
private get;
set;
}
Post a Comment