Difference between Delegate1 =new Delegate1(fun) and Delegate1=fun; [duplicate] - c#

This question already has answers here:
C# Delegate Instantiation vs. Just Passing the Method Reference [duplicate]
(3 answers)
Closed 7 years ago.
I have a small doubt, while initializing delegates we usually use =. What is the difference between the cases below. Both Work same.
public delegate void sam(int i);
//variant 1
s = new sam(fun);
//variant 2
s = fun;

There is no difference between both of them. Both generate the same IL code but the second variant needs C# 2.0 and newer.

Consider this code:
sam s = new sam((i) => { });
s = (i) => { };
Both of them is same.

Related

Is it possible to add methods into variables [duplicate]

This question already has answers here:
Easiest way to extend a Struct (PointF)
(3 answers)
Extension methods versus inheritance
(9 answers)
Extend an existing struct in C# to add operators
(7 answers)
A way to extend existing class without creating new class in c#
(3 answers)
Closed 1 year ago.
Is it possible to add methods into variables, example being.
public static int BoolToInt(bool entry)
{
if(entry == true) { return 1; }
else { return 0; }
}
bool example = checkbox1.Checked;
RandomMethod(example.BoolToInt());
Looking into minimizing visual clutter and help readability (I find RandomMethod(example.BoolToInt(), example2.BoolToInt()); easier to read than RandomMethod(BoolToInt(example), BoolToInt(example2));) I was wondering if this was possible, upon research I found this Can you assign a function to a variable in C#? which feels like it's the right direction, but it makes the variable become the method, when I want to just add into it. I'm a newbie so I couldn't go from there to what I want nor know if it's theres a way to do it, also couldn't find much reading the Microsoft Docs.
You can use C# extension methods to "extend" exists types by declaring new methods for the extended type.
static class BoolExtensions {
public static int ToInt(this bool value) {
return value ? 1 : 0;
}
}
Then you can use as:
var example = true;
var exampleAsInt = example.ToInt();
Reference:
Extension methods

Refactor method (C#) [duplicate]

This question already has answers here:
Simply check for multiple statements C#
(2 answers)
C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]
(2 answers)
Closed 3 years ago.
I have got method:
private bool MyMethod(PlantType plantType)
{
return plantType.PlantMoveType == PlantMoveType.PlantReady
|| plantType.PlantMoveType == PlantMoveType.PlantRelase
}
Can I write it into other way? Maybe with LINQ?
One way is to put the enum values that you want to check against into an array, and call Contains.
return new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
If you are using C# 7 or later, you can also write the method as expression-bodied:
private bool MyMethod(PlantType plantType) =>
new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
Well a small simplification would be to pass the type (enum?) of the property PlantMoveType instead of PlantType as the parameter.
Beyond that, you could declare the types to check for as e.g. an array. In case you'd like to reuse that array, you can also declare it outside the scope of the method:
private static PlantMoveType[] _plantStates =
new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};
private bool MyMethod(PlantMoveType plantMoveType)
{
return _plantStates.Contains(plantMoveType);
}

Can IEnumerable be an alternative to Params[]? [duplicate]

This question already has answers here:
Why use the params keyword?
(11 answers)
Closed 7 years ago.
Can IEnumerable be a possible alternative to params[]?
Because Ive been hearing some articles that params is not good, but I seem to doubt it because it is syntactically straightforward and is very useful.
ex.
public void testMeth(IEnumerable<object> testerEnum){
//Code here
}
Using the params keyword importantly allows callers of your method not to wrap the arguments into a collection at all.
With:
public bool testMeth(params object[] input){
// ... things
return purity >= REQUIRED_PURITY; //this is how to test meth, right?
}
The caller can call
var is_good = testMeth("apples", new object(), 7);
with no need to make their own array.

In C# it's better define object's attribute in its initialization or with dot notation? [duplicate]

This question already has answers here:
Object initializer performance
(7 answers)
Closed 9 years ago.
What is more efficent between this:
MyClass foo = new MyClass()
{
name = "foo",
color = "blue",
number = 3
};
and this:
MyClass foo = new MyClass();
foo.name = "foo";
foo.color = "blue";
foo.number = 3;
Difference between first and second is, that the second way won't create a temporary object (as explained here: CA2000 - "out-of-school-junior-programmers"-mistakes or false positive?) - so no problems, warning or errors when it comes to disposing My Class.

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

This question already has answers here:
With block equivalent in C#?
(19 answers)
Closed 9 years ago.
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?
It's not equivalent, but would this syntax work for you?
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
C# doesn't have an equivalent language construct for that.
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..
I think the equivalent of the following VB:
With SomeObjectExpression()
.SomeProperty = 5
.SomeOtherProperty = "Hello"
End With
Would be this is C#:
{
Var q=SomeOtherExpression();
q.SomeProperty = 5;
q.SomeOtherProperty = "Hello";
}
The only real difference is that in vb, the identifier doesn't have a name "q", but is simply a default identifier used when a period is encountered without any other identifier before it.
There's no equivalent to With ... End With in C#.
Here's a comparison chart for you that illustrates differences between Visual Basic and C#.
There is no equivalent structure in C#. This is a Visual Basic 6.0 / VB.NET feature.

Categories