Home » c# » With block equivalent in C#?

With block equivalent in C#?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#?

Thanks

Answers:

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…)

Questions:
Answers:

This is what Visual C# program manager has to say:
Why doesn’t C# have a ‘with’ statement?

Many people, including the C# language designers, believe that ‘with’
often harms readability, and is more of a curse than a blessing. It is
clearer to declare a local variable with a meaningful name, and use
that variable to perform multiple operations on a single object, than
it is to have a block with a sort of implicit context.

Questions:
Answers:

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.

Questions:
Answers:

No, there is not.

Questions:
Answers:

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; 

Questions:
Answers:

You could use the argument accumulator pattern.

Big discussion about this here:

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx

Questions:
Answers:

Most simple syntax would be:

{
    var where = new MyObject();
    where.property = "xxx";
    where.SomeFunction("yyy");
}

{
    var where = new MyObject();
    where.property = "zzz";
    where.SomeFunction("uuu");
}

Actually extra code-blocks like that are very handy if you want to re-use variable names.

Questions:
Answers:

Sometimes you can get away with doing the following:

var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...

(Code sample for EPPLus @ http://zeeshanumardotnet.blogspot.com)

Questions:
Answers:

I was using this way:

        worksheet.get_Range(11, 1, 11, 41)
            .SetHeadFontStyle()
            .SetHeadFillStyle(45)
            .SetBorders(
                XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick
                , XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick)
            ;

SetHeadFontStyle / SetHeadFillStyle is ExtMethod of Range like below:

 public static Range SetHeadFillStyle(this Range rng, int colorIndex)
 {
     //do some operation
     return rng;
 }

do some operation and return the Range for next operation

it’s look like Linq 🙂

but now still can’t fully look like it — propery set value

with cell.Border(xlEdgeTop)
   .LineStyle = xlContinuous
   .Weight = xlMedium
   .ColorIndex = xlAutomatic

Questions:
Answers:

If there are multiple levels of objects you can get similar functionality with the “using” directive:

using System;
using GenderType = Hero.GenderType; //This is the shorthand using directive
public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var myHero = new Hero();
        myHero.Name = "SpamMan";
        myHero.PowerLevel = 3;
        myHero.Gender = GenderType.Male; //instead of myHero.Gender = Hero.GenderType.Male;
    }
}
public class Hero
{
    public enum GenderType
    {
        Male,
        Female,
        Other
    }
    public string Name;
    public int PowerLevel;
    public GenderType Gender;
}

Questions:
Answers:

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" };