Sunday, November 12, 2017

Nullable in C#

Nullable is a special generic class meant to enable value types to be set to null.

Nullable<bool> nullableOfBool = false;
Nullable<int> nullableOfInt = 0;
Nullable<float> nullableOfFloat = 0.0f;

bool? nullableOfBool = false;
int? nullableOfInt = 0;
float? nullableOfFloat = 0.0f;

As you can see you can initialize them like if they were value types. Moreover, you can treat them like value types as long as you don't mix them with actual value types:

int? v1 = 1;
int? v2 = 7;
int? result = v1 + v2;

If for some reason you wanna access underlying type, you can do this by accessing Value property of Nullable:

int v1 = 1;
int? v2 = 7;
int result = v1 + v2.Value;

Or simply cast it to a corresponding value type:

int v1 = 1;
int? v2 = 7;
int result = v1 + (int)v2;

If you don't know if your nullable contains any value, use can check it using HasValue property.

Null-conditional operator in C#

Null-conditional operator is a new .NET feature meant to ease your life as a developer. Its primary purpose is NullReferenceException prevention. I'mma give you an example:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // This is where you omitted check for null.
            string brand = car.Brand; // And this is where you get into trouble.
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Now we can either add missing check or use null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // Null-conditional operator checks if car is null and if it is,
            // prevents us from accessing Brand property and sets brand to null.
            string brand = car?.Brand;
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Let's slightly modify our example so you can see another use case of null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCars(Car[] cars)
        {
            // Null-conditional operator checks if cars array is null and if it is,
            // prevents us from accessing its first element and returns null.
            Car car = cars?[0];
        }
        static void Main(string[] args)
        {
            DoSomethingWithCars(null);
        }
    }
}

As you can see null-conditional operator can be used with both dot operator and subscript operator (square brackets).

Default values in C#

Here is the thing, C# doesn't allow you to leave a variable unitialized. What I mean is that every time you create a variable it's automatically assigned some sorta default value.

Integral types:
sbyte 0
byte 0
short 0
ushort 0
int 0
uint 0
long 0l
ulong 0ul

Floating-point types:
float 0.0f
double 0.0d
decimal 0.0m

Boolean:
bool false

Any class, struct, including these two:
object null
string null

Enumerations:
enum 0 (value of the first enumerator)

Characters:
char '\0'

Thursday, October 26, 2017

Tiny SSH client in C#

There is very nice SSH library for .NET called SSH.NET. You can find it here:
https://github.com/sshnet/SSH.NET, also available as a nuget package, so you can install it in a couple of clicks. Here is a brief client example:

using Renci.SshNet;
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter IP:");
            var ip = Console.ReadLine();

            Console.WriteLine("Enter username:");
            var username = Console.ReadLine();

            Console.WriteLine("Enter password:");
            var password = Console.ReadLine();

            using (var client = new SshClient(ip, username, password))
            {
                client.Connect();

                while (true)
                {
                    var input = Console.ReadLine();
                    if (input.Contains("exit my console app"))
                        break;

                    Console.WriteLine(client.RunCommand(input).Result);
                }
            }
        }
    }
}

OpenVPN Jumpstart

Yesterday I badly needed to establish VPN connection between two computers, nothing extraordinary, one server and one client. In order to accomplish this quite trivial task I created a key:

openvpn --genkey --secret whatever.key

and two configuration files for the server(192.168.1.1):

dev tun
ifconfig 10.0.0.1 10.0.02
secret whatever.key

and the client(192.168.1.2) respectively:

remote 192.168.1.1
dev tun
ifconfig 10.0.0.2 10.0.01
secret whatever.key

Then I just ran:

openvpn --config server.conf
openvpn --config client.conf

and surprisingly it worked :)

By the way, if you have some kinda firewall or something you might need to consider opening port 1194.

Expression Bodied Functions and Properties in C#

Since C# 6 you can take advantage of using much more laconic expression bodied functions. Oh, expression bodied basically means lambdish or just bodiless :)

using System;

namespace ConsoleApp
{
    class Program
    {
        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod("Hello!");
        }
    }
}

That shortened syntax can also be used to create a getter-only property:

using System;

namespace ConsoleApp
{
    class Program
    {
        static string ExpressionBodiedReadOnlyPrpoperty => "Hello!";
        /*static string ExpressionBodiedReadOnlyPrpoperty { get; } = "Hello!";*/

        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod(ExpressionBodiedReadOnlyPrpoperty);
        }
    }
}

Thursday, October 19, 2017

Async and Await in C#

It's possible to do asynchronous programming in C#. In order to ease your life a little bit they came up with the idea to add a couple of extra keywords: async and await.

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = DoSomeJobAsync().Result;

            Console.WriteLine("Result: " + result);
        }

        async static Task<int> DoSomeJobAsync() {
            return await Task.Run(() => { return 777; });
        }
    }
}

So, to tell compiler you want your method to be "asynchronous" you have to prepend it with async keyword which enables you to use await keyword inside it in order to create so-called suspension point which is basically the asynchronous equivalent of  blocking. The whole concept is meant to manage asynchronous and synchronous calls separately, but I'll tell you what, it's impossible and if you disagree, take a look at what happens in Main. As we cannot use await in synchronous method we are forced to block until we get the result from asynchronous chain of methods.