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

Searching for elements in arrays in C# .NET

The Array class has a number of useful static methods. A group of them is used for searching purposes. The method names are generally quite descriptive. Here are some them with comments in the code:

string[] bands = new string[6] { "Queen", "ACDC", "Metallica", "Genesis", "INXS", "Motörhead" };

//find the first entry in the array which starts with Q, finds "Queen"
string firstBandStartingWithQ = Array.Find<string>(bands, s => s.StartsWith("Q"));
//finds last entry start with M, finds Motörhead
string lastBandStartingWithM = Array.FindLast<string>(bands, s => s.StartsWith("M"));
//finds Metallica and Motörhead and puts them in an array
string[] allWithM = Array.FindAll<string>(bands, s => s.StartsWith("M"));
//index will be 0 as Queen is the first item in the array
int queenIndex = Array.FindIndex<string>(bands, s => s == "Queen");
//yields true as ACDC figures in the array
bool acdIsThere = Array.Exists<string>(bands, s => s == "ACDC");	

View all various C# language feature related posts here.

Extension methods in C#

Introduction

Extension methods in C# allow you to extend the functionality of types that you didn’t write and don’t have direct access to. They look like integral parts of any built-in classes in .NET, e.g.:

DateTime.Now.ToMyCustomDate();
string.ToThreeLetterAbbreviation();

You can extend the following types in C#:

  • Classes
  • Structs
  • Interfaces

You can extend public types of 3rd party libraries. You can also extend generic types, such as List of T and IEnumerable of T. You cannot extend sealed classes.

Read more of this post

Introduction to CouchDB with .NET part 25: connecting to CouchDB from .NET

Introduction

In the previous post we looked at how cookie based authentication works in the CouchDB API. This type of authentication follows a popular model in APIs. The user of the API will first need to acquire a temporary authentication cookie or token. This token must then be attached to the subsequent calls to the API as a means of authentication without sending the username and password in the request. Authentication cookies typically have an expiration date of some minutes. In CouchDB this is set to 10 minutes by default.

In this post we’ll look at how to connect to CouchDB from a .NET project. This is also the final post in this introductory series.

Read more of this post

Replacing substrings using Regex in C# .NET: date format example

Say your application receives the dates in the following format:

mm/dd/yy

…but what you actually need is this:

dd-mm-yy

You can try and achieve that with string operations such as IndexOf and Replace. You can however perform more sophisticated substring operations using regular expressions. The following method will perform the required change:

private static string ReformatDate(String dateInput)
{
	return Regex.Replace(dateInput, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b"
		, "${day}-${month}-${year}");
}

Calling this method with “10/28/14” returns “28-10-14”.

View all posts related to string and text operations here.

Replacing substrings using Regex in C# .NET: string cleaning example

We often need to sanitize string inputs where the input value is out of our control. Some of those inputs can come with unwanted characters. The following method using Regex removes all non-alphanumeric characters except for ‘@’, ‘-‘ and ‘.’:

private static string RemoveNonAlphaNumericCharacters(String input)
{
	return Regex.Replace(input, @"[^\w\.@-]", string.Empty);
}

Calling this method like…

string cleanString = RemoveNonAlphaNumericCharacters("()h{e??l#'l>>o<<");

…returns “hello”.

View all posts related to string and text operations here.

Join custom objects into a concatenated string in .NET C#

Say you have the following Customer object with an overridden ToString method:

public class Customer
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string City { get; set; }

	public override string ToString()
	{
		return string.Format("Id: {0}, name: {1}, city: {2}", Id, Name, City);
	}
}

Read more of this post

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: