Overriding explicit and implicit conversion in C# .NET

Custom implicit and explicit conversions for numeric types can be defined in C# quite easily. You need to be aware of the “implicit”, “explicit” and “operator” keywords.

Consider the following class:

public class Measurement
{
	public int Value { get; set; }
}

Read more of this post

Combinable enumerations in C# .NET

You’ve probably encountered cases with combined enum values using the pipe character, i.e. the “bitwise or” operator ‘|’:

Size.Large | Size.ExtraLarge

Let’s see an example of how to create such an enum.

The enumeration is decorated with the Flags attribute like in the following example:

Read more of this post

How to pass any number of parameters into a method in C# .NET

You must have come across built-in methods in .NET where you can send any number of arguments into a method. E.g. string.Format has an overload where you can pass in a format string and then an array with the “params” modifier.

There’s nothing stopping you from using the same keyword to write a similar method, here’s an example:

public void MethodWithParams(int toBeMultiplied, params int[] multipliers)
{
	foreach (int m in multipliers)
	{ 
		Console.WriteLine(string.Format("{0} x {1} = {2}", toBeMultiplied, m, toBeMultiplied * m));
	}
}

Read more of this post

Implementing an indexer for your object with C# .NET

Indexers are used extensively when accessing items in an array or List:

Friend f = friends[2];

It’s fairly easy to implement your own indexer. Imagine a table with guests sitting around. We could implement an indexer to easily access guest #n.

The Guest object is simple with only one property:

public class Guest
{
	public string Name { get; set; }
}

Read more of this post

Checking for arithmetic overflow in C# .NET

As you know primitive numeric types in C# – and other modern programming languages – have maximum and minimum values that can be stored in memory. If you’re trying to store a larger number in the variable then you’ll get an overflow with unexpected results.

Let’s see an example with the “byte” type. It is actually not one of the primitive types, like int or long, but simply a keyword for an integral type to store the numbers 0-255. Why 255? 1 byte consists of 8 bits and 8 bits in the computer’s memory allows us to store 255 as the highest number. 255 in binary is all 1’s for all 8 bits:

11111111

What happens if we add 1 to that? On paper we can easily solve it by some basic binary maths:

11111111
+ 00000001
===========
100000000

Read more of this post

Compose extremely large integers using BigInteger in C# .NET

The largest integer that can be stored in a long, i.e. a 64-bit integer is 9,223,372,036,854,775,807 in .NET. That is a very large number that will be enough for most applications out there.

However, sometimes it’s not enough and you need to handle something larger. This article on Wikipedia shows several use cases where this can occur. .NET also provides the float and double numeric types that provide much larger ranges. They won’t be integers exactly but they may suit your needs anyhow.

The .NET framework has an object called BigInteger that lets you construct arbitrarily large integers. This object resides in the System.Numerics namespace so you’ll need to reference the System.Numerics.dll library.

Read more of this post

Read the byte array representation of a C# date time

In this post we saw how to extract the byte array representation of primitive types in C#. Here we’ll look at how to do the same with DateTime objects.

DateTimes are not primitive types so the BitConverter.GetBytes method has no overload for it. Therefore we’ll need to go through some more steps. We’ll convert the date into its 64-bit (long) representation. The long can then be supplied to the GetBytes method:

DateTime utcNow = DateTime.UtcNow;
long utcNowAsLong = utcNow.ToBinary();
byte[] utcNowBytes = BitConverter.GetBytes(utcNowAsLong);

utcNowAsLong is a very large integer. It was 5247234542978972986 at time of running the code example. Then we get the bytes using GetBytes which will return a byte of 8 elements as a long is a 64-bit / 8-byte integer.

The reverse operation mirrors what we did above:

long utcNowLongBack = BitConverter.ToInt64(utcNowBytes, 0);
DateTime utcNowBack = DateTime.FromBinary(utcNowLongBack);

“utcNowBack” and the original “utcNow” will be set to the same time.

View all various C# language feature related posts here.

Read the byte array representation of a C# base type

The BitConverter class has a static GetBytes method that has overloads to accepts all the primitive types in C#: int, long, uint, char, bool, ulong, double, float, short, ushort. The method returns the byte array representation if the supplied primitive type.

Here comes an example:

private static void ReadByteArrayFromTypes()
{
	int value = 15;
	byte[] bytesOfValue = BitConverter.GetBytes(value);
}

Read more of this post

Overriding the + and – operators in C# .NET

It’s easy to override the mathemtical operators like + or – in C# to build custom operations.

Consider the following simple Rectangle class:

public class Rectangle
{
	public Rectangle(int width, int height)
	{
		Height = height;
		Width = width;
	}

	public int Width
	{
		get;
		set;
	}

	public int Height
	{
		get;
		set;
	}
}

Read more of this post

The Conditional attribute to control execution of parts of the code in C# .NET

In this post we saw how to use the #if preprocessor to control the execution of code. The compiler will understand those instructions and compile away bits of code.

There’s another way to achieve something similar using the Conditional attribute. You can decorate methods with this attribute. It accepts a string parameter which defines the name of the symbol that must be defined in order for the method to be carried out.

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.