Getting the name of a variable in C# 6 using nameof

C# 6 makes it easy to retrieve the name of a parameter using the nameof keyword. Here comes a situation where it can come handy.

Consider the following Person class with C# 6:

public class Person
{
	public int Age { get; }
	public string FirstName { get;}
	public string LastName { get; }

	public Person(string firstName, string lastName, int age)
	{
		FirstName = firstName;
		LastName = lastName;
		Age = age;
	}
}

Simple, right? Now let’s say you’d like to add some parameter validation to the constructor:

Read more of this post

How to assign an expression to a method in C#6

In this post we saw how to assign expressions to class properties in C# 6 using the lambda operator “=>”:

public string FullName => string.Format("{0} {1}", FirstName, LastName);

This property getter was part of a Person class:

public class Person
{
	public int Age { get; }
	public string FirstName { get;}
	public string LastName { get; }
        public string FullName => string.Format("{0} {1}", FirstName, LastName);

	public Person(string firstName, string lastName, int age)
	{
		FirstName = firstName;
		LastName = lastName;
		Age = age;
	}
}

The same type of syntax exists for one-liner functions. It’s really just syntactic sugar which saves you a return statement and the brackets.

Read more of this post

How to assign an expression to a class property in C#6

Consider the following Person class written using the new immutable property syntax of C# 6:

public class Person
{
	public int Age { get; }
	public string FirstName { get;}
	public string LastName { get; }

	public Person(string firstName, string lastName, int age)
	{
		FirstName = firstName;
		LastName = lastName;
		Age = age;
	}
}

Then let’s say you’d like to add a new property that returns the full name of the person. In C# 5 you’d write something like this:

public string FullName
{
	get
	{
		return string.Format("{0} {1}", FirstName, LastName);
	}
}

Note that the “get” body is very simple, it’s only one line.

In C# 6 we can assign expressions to properties using the familiar “=>” operator as follows:

public string FullName => string.Format("{0} {1}", FirstName, LastName);

How neat is that? You can call this property on the Person object as you would in any other case:

Person p = new Person("John", "Smith", 28);
Console.WriteLine(p.FullName);

…which prints John Smith as expected.

Let’s add one more example. We’ll add an Old property with a simple logic. Anyone over and above the age of 35 will be old. That includes me as well, don’t worry:

public bool Old => Age > 35;

Calling p.Old on the above example will return false.

View all various C# language feature related posts here.

How to create immutable objects in C# 6

In C#5 you would write a Person class with immutable properties with getters as follows:

public class Person
{
    private readonly string _name;
    private readonly int _age;

    public Person(string name, int age)
    {
        _name = name;
        _age = age;
    }

    public string Name
    {
        get
        {
            return _name;
        }
    }

    public int Age
    {
        get
        {
            return _age;
        }
    }
}

The readonly keyword will make sure that the private properties can only be assigned from the constructor. If try the following…

public int Age
{
    get
    {
        return _age;
    }
	set
	{
		_age = value;
	}
}

…you’ll get a compiler error:

“A readonly field cannot be assigned to (except in a constructor or a variable initializer)”

A more simple way to achieve the same might be the “private set” construction:

public class Person
{
	public int Age { get; private set; }
	public string Name { get; private set; }

	public Person(string name, int age)
        {
           Name = name;
           Age = age;
        }		
}

However, the Age and Name fields can still be modified within the Person class:

public string Greet()
{
	Name = "Jill";
	return string.Format("Hello from {0}", Name);
}

You’ll probably guess what the following will output:

static void Main(string[] args)
{
	Person p = new Person("John", 28);
	Console.WriteLine(p.Greet());

	Console.ReadKey();
}

That’s right, “Hello from Jill” which is a bit unexpected from the caller’s point of view.

C#6 comes to the rescue in the following form:

public class Person
{
	public int Age { get; }
	public string Name { get;}

	public Person(string name, int age)
	{
		Name = name;
		Age = age;
	}
}

The Age and Name fields can be set in the constructor but not anywhere else. The Greet() method will fail with the following compiler error:

“Property indexer ‘Person.Name’ cannot be assigned to — it is read only”

View all various C# language feature related posts here.

Joining unique values from two sequences with the LINQ Union operator

Say you have two sequences of the same object type:

string[] first = new string[] {"hello", "hi", "good evening", "good day", "good morning", "goodbye" };
string[] second = new string[] {"whatsup", "how are you", "hello", "bye", "hi"};

You’d then like to join the two sequences containing the values from both but filtering out duplicates. Here’s how to achieve that with the first prototype of the LINQ Union operator:

Read more of this post

Projection in LINQ C# with the SelectMany operator

The SelectMany operator creates a one-to-many output projection sequence over an input sequence. SelectMany will return 0 or more output elements for every input element. Let’s see an example.

Data source:

string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers"
, "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears"
, "Deep Purple", "KISS"};

Consider the following code:

Read more of this post

Using client certificates in .NET part 9: working with client certificates in OWIN/Katana III

Introduction

In the previous post we added a couple of components necessary to add client certificate authentication into the OWIN middleware chain. We haven’t yet put the elements to work though. That is the main topic of this post which will finish this series. We’ll also run a couple of tests.

Have the demo application open in Visual Studio in administrator mode.

Read more of this post

Converting a sequence of objects into a Lookup with LINQ C#

A Lookup in .NET is one of the lesser known data structures. It is similar to a Dictionary but the keys are not unique. You can insert multiple elements for the same key.

Say you have the following object and collection:

Read more of this post

Using client certificates in .NET part 8: working with client certificates in OWIN/Katana II

Introduction

In the previous post we started adding the necessary OWIN-related libraries to our Web API project: a couple of NuGet libraries and the Startup class. We publish our application to the local IIS and it doesn’t allow us to break the code within Startup.cs. We’ll soon see that we can still debug the OWIN components further down the call stack.

In this post we’ll add the necessary elements to a client certificate based authentication in .NET MVC with OWIN.

Read more of this post

4 ways to enumerate processes on Windows with C# .NET

The Process object in the System.Diagnostics namespace refers to an operating-system process. This object is the entry point into enumerating the processes currently running on the OS.

This is how you can find the currently active process:

Process current = Process.GetCurrentProcess();
Console.WriteLine(current);

…which will yield the name of the process running this short test code.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.