I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#?
Thanks
I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#?
Thanks
You could use the argument accumulator pattern.
Big discussion about this here:
http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx
hmm. I have never used VB.net in any depth, so I'm making an assumption here, but I think the 'using' block might be close to what you want.
using defines a block scope for a variable, see the example below
using ( int temp = someFunction(param1) ) {
temp++; // this works fine
}
temp++; // this blows up as temp is out of scope here and has been disposed
Here is an article from Microsoft that explains a bit more
EDIT: yeah, this answer is wrong - the original assumption was incorrect. VB's 'WITH' is more like the new C# object initialisers:
var yourVariable = new yourObject { param1 = 20, param2 = "some string" };
About 3/4 down the page in the "Using Objects" section:
VB:
With hero
.Name = "SpamMan"
.PowerLevel = 3
End With
C#:
//No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;
Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:
var foo = new Foo { Property1 = value1, Property2 = value2, etc };
See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.
(Disclaimer - yes, it's in my interests to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)
ever heard of a fluent-interface? ... that is really near to that ...
This is what Visual C# program manager has to say: Why doesn't C# have a 'with' statement?
As the Visual C# Program Manager linked above says, there are limited situations where the With statement is more efficient, the example he gives when it is being used as a shorthand to repeatedly access a complex expression.
Using an extension method and generics you can create something that is vaguely equivalent to a With statement, by adding something like this:
public static T With<T>(this T item, Action<T> action)
{
action(item);
return item;
}
Taking a simple example of how it could be used, using lambda syntax you can then use it to change something like this:
updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
updateRoleFamily.RoleFamilyCode = roleFamilyCode;
To this:
updateRoleFamily.With(rf =>
{
rf.RoleFamilyDescription = roleFamilyDescription;
rf.RoleFamilyCode = roleFamilyCode;
});
On an example like this the only advantage is perhaps a nicer layout, but with a more complex reference and more properties it could well give you more readable code.