How amazing C#/.Net is ? Part 1

Beribey
5 min readDec 29, 2020

--

These “cool” (but less well-known) things help make the code faster; the code is easier to read and understand. In the comparison process, I mentioned convenience when developing with C # compared to “other languages.”

Photo by Marcus Urbenz on Unsplash

1. Keyword “var” Anonymous Object

In the past, when declaring a variable, we had to declare the type of that variable (here is the stream).


Stream stream = new FileStream(“C:\\abc.txt”, FileMode.CreateNew);

However, with the var keyword, we can declare the variable without caring about the type. The command prompt functions are still performed normally.

var stream = new FileStream(“C:\\abc.txt”, FileMode.CreateNew);

Combined with an anonymous object, we can declare an object with predetermined properties, no need to declare class:

var sampleObj = new { FirstProp = "A", SecondProp = "B"};

This Anonymous object can be serialized to XML, JSON. It can be said that the keyword “var” is salvation for “lazy” developers like me. (in Java, there is no anonymous object as well as this keyword “var”).

2. Automatically create Properties

When we learned about university encapsulation, we were all taught not to access the object’s field directly but through the following methods.

public class Student
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}

With C #, when we declare an auto-property, the language will create a private field, getter, and setter for that field. We can also set private for that getter and setter. The new code is as follows:

public string Name { get; set; }

public string Name { get; private set; } //Field is read only, private setter

3. using blocks

Once upon a time, when there was no useuse, we often wanted to close a stream or connection every time we often put it in a try / finally block.

try
{
stream = new FileStream("C:\\abc.txt", FileMode.CreateNew);
stream2 = new FileStream("C:\\abc2.txt", FileMode.CreateNew);
//Do some readding
}
finally
{
if (stream != null) stream.Close();
if (stream2 != null) stream2.Close();
}

After a while, this pile of code will be quite messy. With using, there is no need to worry about closing the connection manually, and the code is much shorter and easier to understand

using(var stream = new FileStream("C:\\abc.txt", FileMode.CreateNew))
using(var stream2 = new FileStream("C:\\abc.txt", FileMode.CreateNew))
{
//Do some readding
}

4. Measure time with class Stopwatch

Measuring the time a method runs with just 2 lines, StartNew, and Stop, is extremely simple.

var sw = Stopwatch.StartNew();
DoSomething();
sw.Stop();
Console.WriteLine("Time elapsed: " + sw.ElapsedMilliseconds);

5. Ternary operators, null operator

Usually, when assigning a default value to a null variable, we set it to one of the following two ways

if (input == null)
{
input = "default";
}

input = input != null ? input : "default";

With C #, we have the null operator, which makes the code shorter and easier to read

input = input ?? "default"; // If index is null, set by default

Implementing a small operator like this in the language shows that Microsoft developers are very mindful of our developer community.

6. Initialize objects and collections

Usually, when initializing objects and properties, we do the following

Student student = new Student();
student.Name = "John";
student.Age = 10;

With C #, things become simpler and more concise:

Student student = new Student { Name = "John", Age = 10};

You may ask: Why not create a constructor for the object, that’s all. I would like to answer: When creating a constructor, we must declare all parameters passed. This way, we can pass as many parameters as we want (For example, the student object has 10 fields, we only want to set 2 fields).

Next is to initialize a collection, the usual way and the C # way. Which way is short, easier to understand than you see for yourself.

// Old way
List <string> list = new List <string> ();
list.Add ("string 1");
list.Add ("string 2");
list.Add ("string 3");

// New way
List <string> list = new List <string> {"string 1", "string 2", "string 3"};

Combines both classes and collections

List<Student> list = new List<Student>
{
new Student { Name = "Student 2", Age = 2},
new Student { Name = "Student 3", Age = 4}
};

7. Extension method

In some cases, we want to add methods for some sealed classes, or classes from other libraries. In some languages, this is not possible, but with C # we can use the extension method.

For example, here, we have a Student class from another library, unable to edit the code. We want to add the Print method.

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}

We create an extenstion class, this class must be a static class, the method must also be static, the first parameter passed is the class that needs an extension, with the keyword this.

public static class StudentExtension
{
public static void Print (this Student student)
{
Console.WriteLine (student.ToString ());
}
}

//Use
var student = new Student ();
student.Print ();

8. LINQQQQ

Actually, there is only 1 letter q, but since this is one of C #’s extremely cool things, I emphasize.

Linq is quite easy to use, but in order to understand it you need to know about Predicate, Func, lambda etc, I will spend 1 article to say more. Here I just introduce fear, why it is good.

In the old days, when we didn’t have linq, let’s say we wanted to find students aged <20 in the list, we needed to write long code like this:

var studentsUnder19 = new List<Student>();
foreach (var student in students)
{
if (student.Age < 19) studentsUnder19.Add(student);
}

With LinQ, we only need one line of code:

var studentsUnder20 = students.Where(student => student.Age < 20);

That’s just one of the many cool features of Linq, I’ll say it more in another article. (In a small way, in javascript we can use an underscore library to have similar features. In Java 7 and below, there is no Linq, from Java 8 and above we just started adding Linq to mimic C #).

See you in part 2.

--

--

Beribey

Always be nice to anybody who has access to my toothbrush.