It is difficult to separate exactly what is exactly sugary from what is not. It is also difficult to define all the sweets of C#, but here are some that make the code much clearer.
lock
That:
lock (_lock)
{
}
In place of:
object obj;
var temp = obj;
Monitor.Enter(temp);
try
{
// body
}
finally
{
Monitor.Exit(temp);
}
foreach
That:
IEnumerable<int> numeros = new int[]
{
1, 2, 3, 4, 5
};
foreach (int i in numeros)
{
}
In place of:
var enumerator = numeros.GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
}
using
That:
using (FileStream f = new FileStream(@"C:\foo\teste.txt", FileMode.Create))
{
}
In place of:
FileStream f2= new FileStream(@"C:\foo\teste.txt", FileMode.Create);
try
{
}
finally
{
f2.Dispose();
}
Auto properties
That:
public string Foo { get; set; }
In place of:
private string _foo;
public string Foo
{
get { return _foo; }
set { _foo = value; }
}
Nullable
That:
int? nullInt2 = null;
In place of:
Nullable<int> nullInt = new Nullable<int>();
Operator `??`
That:
int myNum = nullInt ?? 0;
In place of:
int myNum2 = nullInt == null ? 0 : nullInt.Value;
I changed the response to community wiki to extend and improve
I think this question is too wide. There is no such clear boundary on where "sugar" ends and where "language" begins. For example, the operator
+=
is also sugar. Theusing
is a sweetened version of a code where certain features are released manually. There will be dozens of examples.– bfavaretto
I was just going to ask using if it was a sugar syntactic.
– Guilherme de Jesus Santos
@bfavaretto Having dozens of examples does not make the question too broad. Of course the definition of syntatic sugar is not exact, but even if you consider even example as
+=
(that I don’t think are sugary) the list is finite and well defined.– Gabe