If you’re learning to program in Visual C# for the first time, but you’ve got a background in VB or VBA programming, this is the article for you! It summarises the main concepts which you’ll need to get used to. Let’s begin with the thorny topic of declaring variables, and then move on to case sensitivity.
Declaring Variables
In C# you put the type of the variable first, then its name, and then (optionally) its value. For example:
int i = 1;
This command would create a variable of type int, which is called i and which will hold the value 1.
Case Sensitive Variables
Suppose that you want to create a variable to hold an integer, and you want to call it MyInteger. You type in the following code:
int MyInteger = 0; lblExample.text = myinteger.tostring();
This will give you an error, since MyInteger and myinteger aren’t the same thing. In Visual C#, everything is case sensitive. The good news is that gives you 52 letters to play with, not 26 – the bad news is that you’ll have to write everything carefully.
This keyword
In C#, use this to refer to the current object, rather than me. For example: this.lblExample.text = ‘hello’;
Other changes
The above examples illustrate a number of other changes for Visual C# programming. These include:
- You must end all commands with a semi-colon;
- You must put brackets after certain functions (for example, ToString() above);
- You must use single quotation marks to enclose strings of text.
If Statements
If you want to create an IF condition, you’ll certainly have to learn how to type in curly brackets on your keyboard! Here’s a simple condition:
if (i-1) { lblExample.text = ‘one’; } else { txtExample.text = ‘not one’; }
You can see from the above example that in Visual C# programs the condition has to go in round brackets and the statements which follow the condition have to go in parentheses. You can have an else statement, and this is followed also by a series of statements to be executed in curly brackets.
Other Differences
There are many other differences when you’re programming in Visual C#. For example:
- When you’re looping over collections, you’ll use the for each keyword;
- When you’re declaring arrays or referring to subscripts in arrays, you’ll learn to use square brackets rather than round ones;
- Calls to properties use different syntax (although the concepts are the same)
I find that programming in Visual C# – once I get used to it – is no harder than programming in VB, provided that I remember that everything is case-sensitive!