Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalence of "With...End With" in C#? [duplicate]

I know that C# has the using keyword, but using disposes of the object automatically.

Is there the equivalence of With...End With in Visual Basic 6.0?

like image 439
odiseh Avatar asked Jun 30 '09 12:06

odiseh


3 Answers

It's not equivalent, but would this syntax work for you?

Animal a = new Animal()
{
    SpeciesName = "Lion",
    IsHairy = true,
    NumberOfLegs = 4
};
like image 91
tomfanning Avatar answered Nov 02 '22 09:11

tomfanning


C# doesn't have an equivalent language construct for that.

like image 35
Philippe Leybaert Avatar answered Nov 02 '22 09:11

Philippe Leybaert


There is no equivalent, but I think discussing a syntax might be interesting!

I quite like;

NameSpace.MyObject.
{
    active = true;
    bgcol = Color.Red;
}

Any other suggestions?

I cant imagine that adding this language feature would be difficult, essentially just a preprocessed.

EDIT:

I was sick of waiting for this feature, so here is and extension that achieves a similar behavior.

/// <summary>
/// C# implementation of Visual Basics With statement
/// </summary>
public static void With<T>(this T _object, Action<T> _action)
{
    _action(_object);
}

Usage;

LongInstanceOfPersonVariableName.With(x => {
     x.AgeIntVar = 21;
     x.NameStrVar = "John";
     x.NameStrVar += " Smith";
     //etc..
});

EDIT: Interestingly it seems someone beat me to the punch, again, with this "solution". Oh well..

like image 22
expelledboy Avatar answered Nov 02 '22 09:11

expelledboy