Monday, 29 July 2019

Value, Reference and Out Parameters in C# Programming

Confused by all the parameter types in C#? here’s a quick guide to help you sort out the differences between value, reference and out parameters. This is an extract from my book, The Little Book Of C#.

By default, when you pass variables to functions or methods these are passed as ‘copies’. That is, their values are passed as arguments and these values are assigned to the corresponding parameters declared by the function. Any changes made within the method will affect only the copies (the parameters) within the scope of the method. The original variables that were passed as arguments (and which were declared outside the method) retain their original values.

Sometimes, however, you may in fact want any changes that are made to parameters inside a method to change the matching variables (the arguments) in the code that called the method. In order to do that, you can pass variables ‘by reference’. When variables are passed by reference, the original variables (or, to be more accurate, the references to the location of those variables in your computer’s memory) are passed to the function. So any changes made to the parameter values inside the function will also change the variables that were passed as arguments when the function was called.

To pass arguments by reference, both the parameters defined by the function and the arguments passed to the function must be preceded by the keyword ref. The following examples should clarify the difference between ‘by value’ and a ‘by reference’ arguments. In each case, I assume that two int variables have been declared like this:

int firstnumber;
int secondnumber;
firstnumber = 10;
secondnumber = 20;


Example 1: By Value Parameters

private void ByValue(int num1, int num2) {
    num1 = 0;
    num2 = 1;
}

This method might be called like this:

ByValue(firstnumber, secondnumber);

Remember that firstnumber had the initial value of 10, and secondnumber had the initial value of 20. Only the copies (the values of the parameters, num1 and num2) were changed in the ByValue() method. So, after I call that method, the values of the two variables that I passed as arguments are unchanged:

firstnumber now has the value 10.
secondnumber now has the value 20.

Example 2: By Reference Parameters

private void ByReference(ref int num1, ref int num2) {
    num1 = 0;
    num2 = 1;
}

This method might be called like this:

ByReference(ref firstnumber, ref secondnumber);

Once again, firstnumber has the initial value of 10, and secondnumber has the initial value of 20. But these are now ref parameters, so the parameters num1 and num2 ‘refer’ to the original variables. When changes are made to the parameters, the original variables are also changed:

firstnumber now has the value 0.
secondnumber now has the value 1.

You may also use out parameters which must be preceded by the out keyword instead of the ref keyword.

Example 3: out Parameters

private void OutParams(out int num1, out int num2) {
    num1 = 0;
    num2 = 1;
}

This method might be called like this:

int firstnumber;
int secondnumber;
OutParams(out firstnumber, out secondnumber);

In this case, as with ref parameters, the values of the variables that were passed as arguments are changed when the values of the parameters are changed:

firstnumber now has the value 0.
secondnumber now has the value 1.

At first sight, out parameters may seem similar to ref parameters. However, it is not obligatory to assign a value to a variable passed as an out argument before you pass it to a method. It is obligatory to assign a value to a variable passed as a ref argument.

You can see this in the example shown above. I do not initialize the values of firstnumber and secondnumber before calling the OutParams() method. That would not be permitted if I were using ordinary (by value) or ref (by reference) parameters. On the other hand, it is obligatory to assign a value to an out parameter within the method that declares that parameter. This is not obligatory with a ref argument.

If you need a complete guide to C# programming, my book, The Little Book Of C# is available on Amazon (US), Amazon (UK) and worldwide.

Saturday, 27 July 2019

Learn C# (C-Sharp) In A Day

I know, I know. Unless you are a super-fast learner, you really won't be able to learn very much C# in one day. But if you follow the examples in my new book, you will definitely be able to start writing programs in your first day of study. This is the latest in my series of Little Books of programming. My aim is to keep them short, focused and practical. I know you can get a ton of information online so there's no point padding out these books with class library and syntax references. Instead, each book aims to get you writing - and understanding - programs right away...
This book will teach you to program the C# language from the ground up. You will learn about Object Orientation, classes, methods, generic lists and dictionaries, file operations and exception-handling. Whether you are a new programmer or an experienced programmer who wants to learn the C# language quickly and easily, this is the book for you!

This book explains...

  • Fundamentals of C#
  • Object Orientation
  • Static Classes and Methods
  • Visual Studio & .NET
  • Variables, Types, Constants
  • Operators & Tests
  • Methods & Arguments
  • Constructors
  • Acess Modifiers
  • Arrays & Strings
  • Loops & Conditions
  • Files & Directories
  • structs & enums
  • Overloaded and overridden methods
  • Exception-handling
  • Lists & Generics
  • ...and much more

Buy on Amazon.com, Amazon.co.uk and worldwide.

Tuesday, 16 July 2019

Is an Array in C a Pointer?

In some programming languages, arrays are high-level ‘objects’ and the programmer can think of them simply as ordered lists. In C, you have to deal with arrays ‘as they really are’ because C doesn’t try to hide what is going on ‘close to the metal’. One of the common misconceptions (which I’ve read so many times in books and on web sites that I almost started to believe it was true!) is that array ‘variables’ are ‘special types of pointer’. Well, they aren’t. Not only that, array identifiers aren’t even variables.

Let me explain. Let’s assume you’ve declared an array of chars (C’s version of a string)  called str1 and a pointer to an array of chars, str2:

    char str1[] = "Hello";
    char *str2 = "Goodbye";

An array and an address (in C) are equivalent. So str1 is the address at which the array of characters in the string "Hello" are stored. But str2 is a pointer whose value is the address of the string "Goodbye".

In fact, str1 isn’t a variable because its value (the address of an array) cannot be changed. The contents of the array – its individual elements – can be changed. The address of the array, however, cannot. That is why I prefer to call str1 an array ‘identifier’, though many people would call it, somewhat inaccurately, an ‘array variable’.

But, wait a moment. If the value of an array identifier such as char str1[] and the value of a pointer variable such as char *str2 are both addresses, aren’t str1 and str2 both pointers?

No, they are not.

It is an essential feature of a variable that its value can be changed. The value of an array identifier cannot be changed. What’s more, a pointer variable occupies one address; its value can be set to point to different addresses. But an array identifier and its address are one and the same thing. How can that be?

You have to understand what happens during compilation. When your program is compiled, the array identifier, str1, is replaced by the address of the array. That address cannot be changed when your program is run. But str2 is a pointer variable with its own address. Its value (the address of an array) can change if new addresses are assigned to the pointer variable.

If you need to know more about the mysteries of pointers, arrays and addresses in C, I have a book that explains everything (with all the source code examples for you to download). It’s called The Little Book Of Pointers and it’s available as a paperback or eBook from Amazon (US), from Amazon (UK) and other Amazon stores worldwide.

Friday, 12 July 2019

MAGIX PopUp Ads – how to get rid of them

They are like a virus. They infect your computer and make a damn’ nuisance of themselves by popping up adverts, special offers, upgrade deals and, well, more adverts… Upgrade MovieStudio, Buy Sounds for ACID, Download Stuff for VEGAS, Install Junk I really don’t want for MAGIX Music Maker. The damned adverts pop up at the bottom of the screen almost every time I boot up the computer. If there was ever a way to make the customer hate your products, this is it!

Does anyone really want to see these ads popping up on their PC every day???
Actually, I rather like many MAGIX products. But their persistent, irritating, spammy popup adverts are doing their best to make me change my opinion.

Another day, another ad!!!
But how do I get rid of them? I couldn’t see an option anywhere to “Disable our Spamware”. I ended up having to Google for help. I eventually found that I have to uninstall a piece of junkware called MAGIX Connect. Go to Settings, Apps, MAGIX Connect, Uninstall.

Oh joy! Gone at last!
Hurrah! Now the blasted adverts are gone. What I find truly mysterious about this is that MAGIX can’t see the obvious truth that, far from promoting its software, these nasty, trashy, annoying popups are about the worst sort of bad publicity they could possibly have. As I said, their software is generally good. But as for their Spamware…!!!!

Sunday, 7 July 2019

Learn C Programming, Pointers and Recursion

I’m pleased to announce the launch of Bitwise Books! We’ve been working away at this for most of the last year. Our aim is to publish a range of tightly-focused programming books that explain just what you really need to know without any padding.


The series is called The Little Book Of… and our first three titles are:

The Little Book Of C Programming
Amazon.com
Amazon.co.uk

The Little Book Of Pointers
Amazon.com
Amazon.co.uk

The Little Book Of Recursion
Amazon.com
Amazon.co.uk

In addition, we have created a series of free programming guides called A Really Simple Guide To… These include A Really Simple Guide To Object Orientation, C IDEs and Pointers. To can get the guides delivered straight to your inbox (no purchase necessary) from the Bitwise Books site.

We’ll be announcing more Really Simple Guides and Little Books Of (various programming topics) soon.

Monday, 1 July 2019

Free File Sync and Backup


I live in dread that my PC will suddenly cease to function and I’ll lose all my work. In spite of taking daily incremental backups (I use Macrium Reflect for those), what I would really like is to have complete, uncompressed, unarchived, ready-to-run copies of all my data files on a second PC. So if PC Number One goes wrong, I can just switch over to PC Number Two and carry on working. As I have a lot of data – video files for my courses, document files for my books, plus images, program code and all sorts of other stuff, I really, really don’t want to lose anything.

So recently I’ve been using a rather fine file-copying program called FreeFileSync. This lets you synchronize copies of folders and sub-folders. That means that you can, in principle, have two complete copies of your data and let FreeFileSync work out which are the most recent copies and then update any out-of-date files by copying the newer versions over them. In that way you could work on the same data on two PCs and let FreeFileSync synchronize them.

With FreeFileSync you can create named backup sets and synchronize groups of subfolders across two computers.
In fact, my requirements are a bit simpler. I want one ‘working set’ of data and one copied set of data. So instead of synchronizing in ‘two directions’, both to and from my two PCs, I just want it to keep a ‘backup copy’ on PC Two updated with any changes I make to the files on PC One.

It does a pretty good job of this. My initial backup (340Gb of data over 131,549 files) took over ten and a half hours to complete. Thereafter, however, it only copies any changed files. To do that it does a file comparison which takes just a few minutes and a file copy which again takes seconds or minutes. If you need to maintain multiple copies of your files, I recommend that you try out FreeFileSync. My main criticism, so far, is that it doesn’t have a built-in scheduler. So if you need to do automatic timed backups, you are going to have to do a bit of extra work using the Windows Task Scheduler.

My initial backup was huge as this chart (which shows backup progress) proves. Subsequent backups are much smaller and faster.
Even so, this is a useful tool to have. After all, disaster has a habit of striking just when you least expect it. And you really can’t have too many backups!