Fortsätt till huvudinnehåll

Inlägg

C# Enum as bit field

Bit field enum Whenever you wish to express combinations of properties of an object, bit fields are a good way to accomplish this. As a simple example, consider a file in the file system. It can be Readable , Writable , Hidden or a combination these. The different attributes can be defined as an enum : [Flags] public enum FileAttribute {   None      = 0b0000;   Readable  = 0b0001;   Writeable = 0b0010;   Hidden    = 0b0100; } To indicate that this enum is expected to be used as a bit field I have defined it with the FlagsAttribute . It is important to understand that the FlagsAttribute does nothing more than making some changes to how the ToString method of the enum works, making it possible to print out all flags. It does not introduce any validation or special treatment of the enum in any other way. I have defined the values of the different fields of the enum using binary representation, this shou...

C# Deconstruct and Discards

 Deconstruct and Discards In the last post I mentioned the Deconstruct method and how it should not be mixed up with a Destructor . In this post I will show some examples and how you can use Deconstruct and especially in combination with something called Discards . The Deconstruct method can be defined within a class to provide a way to retrieve a Tuple of the data that makes up the type and Discards can be used by the caller to effectively ignore the members of the Tuple that aren't of interest. Sounds complicated? Hopefully the examples below will clear things out. Implementing the Deconstruct method Let's start with a simple container class holding attributes of a file in the filesystem. public class FileInfo {   public string Name { get; }   public int SizeInBytes { get; }   public bool ReadOnly { get; }   public FileInfo(string name, int sizeInBytes, bool readOnly)   {     Name = name;     SizeInBytes = si...

C# Finalize, Dispose, and Deconstruct

Introducing the Concepts It is easy to get a bit confused when trying to figure out what resources you need to free explicitly and how to release the resources that your class has created or is holding references to. You will find that there is something called Finalizer , a clean-up pattern called The Dispose Pattern, and a special Deconstruct method that you can declare. In most cases though, you don't have to do anything and just let the Garbage Collector (GC) do its thing. However, if your class allocates unmanaged memory, open file handles, network sockets, database connections or similar, you need to ensure that these are properly closed and freed before the references are removed. I will go through the different concepts and hopefully clear out how to ensure that all resources are properly freed in your application. The Deconstruct method You might say that it is incorrect to even mention the Deconstruct keyword/method in this post, since it actually have nothing ...

When to use out parameters in C#

The out keyword In C# you can use the out keyword to define output parameters in your method signature. For example, the Int32.TryParse method in the System namespace has the following signature: public static bool Int32.TryParse(string s, out int result) From this you can read out that the TryParse method returns a boolean but also provides a result as an out parameter . The boolean will indicate whether it was possible to parse an integer value from the string s and store it in the result variable. You can call the TryParse method like this: if (Int32.TryParse(str, out var result)) {     Console.WriteLine($"The result is: {result}"); } else {     Console.WriteLine("Parsing failed"); } When is it a good idea to use out parameters ? Most of the time the use of out parameters adds complexity to your program. It will make the source code harder to follow since anyone reading the code will have to juggle several return values instead of just...

C# Delegates, Action, Func, or Predicate

Introduction As a previous C developer I am used to working with function pointers and I found the C# Delegates quite easy to work with in comparison. One thing that made me a bit confused initially however were the Delegate types defined in the .NET framework. Why would I want to bother with Actions , Funcs , and Predicates ? After reading up on them I almost never define custom Delegates anymore. I will try to explain their use cases below. Delegates A Delegate in C# is similar to a function pointer in C or C++. You can always define a custom Delegate that matches any method signature you want. However, the .NET Framework defines a number of Delegates you can use so that you don't have to define your own. These Delegates are grouped into three different Delegate groups, Actions , Funcs , and Predicates . Actions An Action is, as the name implies, a Delegate that encapsulates a method that performs an operation and where you expect no result to be returned. The Ac...

Override the Object.GetHashCode method, why you should bother

When you design a class you sometimes want to override the Equals method in order to use some internal fields to determine if two instances of the class are equal. For example let's assume that you have implemented a class Money that has two fields, one named _amount of type decimal and another one called _currency of type string . You decide that two objects of type Money are equal if and only if the amount and currency fields have the same values. The implementation of Equals looks like this: public override bool Equals(object obj) { if (obj is Money other) { return _currency.Equals(other._currency, StringComparison.Ordinal) && _amount.Equals(other._amount); } return false; } You then notice that you get a warning during compilation, Warning CS0659 'Money' overrides Object.Equals(object o) but does not override Object.GetHashCode() . So what is this all about? If you look into it a bit you will find that there is a rule sayin...

String comparison in C#

In C#, a string is a sequential read-only collection of Char objects. A Char object is an instance of a Char struct, which represents a character as a UTF-16 code unit. Most programs, and programmers, do not care much about the internal representation of a string and a Char . As long as you know that strings are immutable and there is a big efficiency penalty involved in building up strings in loops without involving a mutable object, such as a StringBuilder , you are mostly fine. However, there are some things that are good to know when working with strings. One of these things is comparison using methods such as S tring.CompareTo and String.Compare . By default the Compare and CompareTo methods are Culture sensitive. This means, that depending on the language and culture setting of the machine running the application , comparison and sorting of strings might be different than on your development machine. This might be exactly what you want, or it might come as a complete surp...

When to use float, double, and decimal in C#

If your dealing with numbers that have fractions you need a number type that can handle that case. When you define a variable in C# and assign it a fractional value, for example var myValue = 2.5; the default type is double . In many cases double works fine. But sometimes you want to use float or decimal instead. The major difference between float and double is that float uses 32 bits while double uses 64 bits. This makes double able to represent a much larger range of values with higher precision. So if memory space is not an issue you can safely ignore float and use double instead. One major drawback with float and double is that they use binary representation for the fractional part of the value. This becomes an issue when you need to have exact values for the fractional part. Not all fractional values, that looks really exact in the code, can be represented in binary. One example is 0.2 which gets rounded off when stored as a float or double. What this means is that y...

Indexers in C#

A feature in the C# language that I have noticed that many developers, even some with years of C# experience, have missed is that it is possible to create Indexers. With Indexers you are able to use square brackets to access specific elements of a class, just like you would in an Array or a List: items =  new   List < int > { 1, 2, 3, 4 }; var  first = items[0]; Assume that you define an interface for a certain ability that a class can have. That ability being that it should be possible to set and get elements of the class using square brackets. You may define the interface like this: namespace  Indexer {      public   interface   IIndexable < T >     {         T   this [ int  index] {  get ;  set ; }     } } And a class can implement the interface like this: using ...

Client package manager for Visual Studio

While following the examples in the Pro ASP.NET Core MVC 2 book I realized that currently it doesn't exist a package manager for JavaScript packages with good integration with Visual Studio. Prior to version 15.5 a package manager named Bower was integrated with Visual Studio. This support was however removed and the plan is to add support for a new package manager, called Library Manager, or LibMan for short in version 15.8 of Visual Studio. But the current version 15.7.4 have no good integration with any JS package manager. So, what can you do about it? Well you can use the Node Package Manager, npm. This has some integration with Visual Studio and adding a package.json to the root of your project lets you specify packages that is downloaded for you. But, the downloaded files are not included in your project, instead they are just downloaded to a folder named node_modules in your project directory. So, how do you add the files you need to your project? Well first of all, be ...

Hurt

I have to take a week off from coding 😢. Today I accidentally cut myself in the hand quite bad while cooking and had to go to the emergency to get stitched back together. Lesson learned, nerds should stay away from sharp objects.

Making some changes to the ASP.NET learning plan

After some thought I have decided to put some more time into the "learning by doing" parts of my focused ASP.NET learning. Even though the Little ASP.NET Core Book is a great resource for getting started quickly with ASP.NET Core it relies heavily on the MVC and Identity templates. Using templates is a nice way to get started quickly, but it also encourages developers to treat important features, such as authentication, as black boxes. I really want to learn things in depth so I will spend some more time on actually writing a couple of sample sites using a Empty template. To help me on my way I have decided to go with the book  Pro ASP.NET Core MVC 2 by Adam Freeman.

ASP.NET Core sample site done

Following the hands-on tutorial in The little ASP.NET Core book I was able to put together a sample ASP.NET site in just a couple of days. The book is targeting ASP.NET Core 2.0 but I attempted to use the latest official release, which at the time of writing is ASP.NET Core 2.1.300. I didn't expect any breaking changes between a version 2.0 and 2.1 but there actually are some things that do not work exactly as they did in 2.0. I have written them down on my GitHub page and there is also a feature request available on the book's GitHub page to change it so it is compatible with version 2.1 of ASP.NET Core. The author of the book, Nate Barbettini, has made a great work and I can really recommend having a look at the book. It is available for free at his website. However, if you want every sample in the book to work without any modifications you should probably use ASP.NET Core 2.0 for now.

Git repository for ASP.NET focused learning

I set up a Git repository on GitHub for the ASP.NET focused learning project, see https://github.com/Backhage/LearnASP.NET . Thanks to the Creative Common licensed book "The little ASP.NET Core book" things are progressing a lot faster than I initially planned. The book is a step-by-step guide that takes you through the details on creating a SQLite backed site with ASP.NET Core MVC. It shows you how to do it and explains why. If you, like me, have a couple of years of C# coding behind you most of the things will be quite easy to grasp. Entity Framework is used to work with the database making it easy to use LINQ queries to access data. The things that are a bit unfamiliar is the front end stuff. I created my first website in 1997 and wrote quite a lot of HTML and even some ASP (the old kind, not the ASP.NET kind), PHP and JavaScript during the years following that. However, I haven't been writing much front end stuff since then. But at least some if it is still fami...

Focused learning, ASP.NET

I have decided that it is time to really broaden my knowledge on a specific topic. With all the things I have going on beside learning new, coding related stuff, stuff (full time work, family with two kids, and marathon training) I need to set up a study plan, goals and set off time for focused learning. The topic I have in mind is Web-based applications. I am thinking ASP.NET, Typescript, and Entity Framework. The application can be my good old friend "The Record Collector". Here's a quick plan, may have to be revised. Weeks Reading material. Collect links, books, etc on the topic. Tooling. Ensure all required tools and resources for developing and hosting a database backed ASP.NET web application are available. Sample site. Follow guide/tutorial to set up a sample site. Domain Model. Design the core domain model for the Record Collector application. Core implementation. Implement core functionality. Focus should not be on UI and persistence. Finish up core ...

Android Studio Impressions

I have some previous experience with Jetbrains IDE for Java development, IntelliJ. And I have a couple of years of experience using their Visual Studio plugin ReSharper. I think both of the products are great and therefore I was happily surprised to see that Android Studio is built on the IntelliJ Platform . If you know IntelliJ you will feel right at home using Android Studio. Of course there are several Android specific features, like automatic install of the Android SDK and support for starting and running your app directly on an Android emulator or on your own Android device. You also have access to a built in layout editor that you can use to design the UI for your app. It has some similarities to the layout view in Visual Studio that you use when designing UIs for WPF applications (like drag and drop of visual components, properties listing, etc). Overall it is pretty neat and easy to understand and work in. Of course you still have the possibility to edit the underlying XM...

Switching to Android Studio

I thought Xamarin.Forms and Visual Studio would be a mature and stable development environment for developing apps for Android, iOS and UWP. I was wrong. First, as I wrote in the previous post, it does not work to start the Android Emulator from within Visual Studio. I filed a bug report towards Visual Studio and was informed that the development team is aware of the issue and are planing to release a fix on the 15.8 branch of VS. Not very prioritized to fix apparently. Second, Xamarin.Forms defaults to using a shared project for the common, not target specific, source files. Shared C# projects uses the new .NET project system by default. The support for XAML and code behind files still has problems in the new system. So, adding new XAML files to your project will not work from within Visual Studio, manual editing of the project files are needed. Also the static code analysis does not work well with XAML files in the new project system so you will get a lot of false errors. Thir...

A mobile app using Xamarin

Today I started on a mobile app for my common-law wife. She is starting a workout program and I thought I could code up a simple Android app that she can use to keep track of the different exercises and the number of repetitions or duration to do them for. As I have been working with C# for couple of years now and I feel comfortable with it I thought I would try using Xamarin . I discussed the functionality for the first version with my partner and sketched up a simple model of the entities. Then I figured it would be a good idea to try out a simple tutorial to get a feeling for it and ensure I have all the needed tools installed. In the Visual Studio Installer there is a check box for mobile app development so I checked that and let everything install. Then in Visual Studio I created a new Android project, built it and pressed F5 to see what would happen. No go! The Android emulator wants virtualization to be enabled in order to run in hardware accelerated mode. So I had to rebo...

To be really proud of your work

This week I was asked, without any preparation time, to explain something that I have coded that I feel really proud over. To me this was a really tough question. I don't normally look back on my coding projects and feel proud over what I have done. When I code things at home I do it for learning, trying out new things or improving my skills in certain areas. And the things I code at work they are, well, just work. I do, however, take pride in my work. In the sense that I put a lot of effort into making good, carefully considered decisions, try to master my craft, and write the best code I can. However, to me this is the base line, not something I only do on selected projects. So it is hard to look back and point out a single project, or piece of code, that I feel really proud over. I can however, think of a couple of projects that didn't turn out so good. Not because we didn't put a lot of effort into them, but because they weren't that good ideas to start with.