Syntactic sugar? [closed]

2

I came across these days with the term syntactic sugar, when I was studying the use of await and async in C #. This question explains what is syntactic sugar or syntax sugar What is syntax sugar and how does it work? .

In addition to await and async , which ones exist in C #?

    
asked by anonymous 27.05.2015 / 21:16

1 answer

1

It is difficult to separate exactly what is exactly sugary than it is not. It's also difficult to define all the candy in C #, but here are some that make the code much clearer.

lock

That:

lock (_lock)
{

}

Instead 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)
{

}

Instead 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))
{

}

Instead of:

FileStream f2= new FileStream(@"C:\foo\teste.txt", FileMode.Create);
try
{

}
finally
{
    f2.Dispose();
}

Auto properties

That:

 public string Foo { get; set; }

Instead of:

private string _foo;
public string Foo
{
    get { return _foo; }
    set { _foo = value; }
}

Nullable

That:

int? nullInt2 = null;

Instead of:

Nullable<int> nullInt = new Nullable<int>();

Operator '??'

That:

int myNum = nullInt ?? 0;

Instead of:

int myNum2 = nullInt == null ? 0 : nullInt.Value;

I have changed the community wiki response so that it is extended and improved

    
27.05.2015 / 23:26