101 Visual Basic And C# Code Samples



last modified Januar 6, 2021

In this part of the C# tutorial, we will cover basic programming conceptsof the C# language. We introduce the very basic programs. We work with variables,constants and basic data types. We read and write to the console; we mentionvariable interpolation.

Both languages are imperative and share the “structured” programming paradigm and a set of basic statements shared among almost all programming languages (for, while, if, etc.). Dim a As Integer = 10 Dim b As Integer = 8 Dim c As Integer = 6 Dim firstPattern, secondPattern, thirdPattern As Integer firstPattern = (a And b) secondPattern = (a And c) thirdPattern = (b And c) The preceding example produces results of 8, 2, and 0, respectively. Logical/Bitwise Operators (Visual Basic) Operator Precedence in Visual.

C# simple example

We start with a very simple code example.

Program.cs

This is our first C# program. It will print 'This is C#' message tothe console. We will explain it line by line.

The using keyword imports a specific namespace toour program. Namespaces are created to group and/or distinguish named entitiesfrom other ones. This prevents name conflicts. This line is a C# statement.Each statement is ended with a semicolon.

We declare a namespace. Namespaces are used to organize code and to preventname clashes.

Each C# program is structured. It consists of classes and its members. A classis a basic building block of a C# program. The above code is a class definition.The definition has a body, which starts with a left curly brace ({) and endswith a right curly brace (}).

The Main is a method. A method is a piece of code created to do aspecific job. Instead of putting all code into one place, we divide it intopieces, called methods. This brings modularity to our application. Each methodhas a body, in which we place statements. The body of a method is enclosed bycurly brackets.

The specific job for the Main method is to start the application.It is the entry point to each console C# program. The method is declared to bestatic. This static method can be called without the needto create an instance of the Program class. First we need start theapplication and after that, we are able to create instances of classes. TheMain method has the args argument, which storescommand line arguments.

In this code line, we print the 'This is C#' string to the console. To print amessage to the console, we use the WriteLine method of the Console class. The class represents the standard input, output, anderror streams for console applications. Note that Console class ispart of the System namespace.This line was the reason to import the namespace with the using System;statement. If we didn't use the statement, we would have to use the fully qualifiedname of the WriteLine method: System.Console.WriteLine('This is C#');.

C# top-level statements

C# 9.0 introduced top-level statements; these allow us to eliminate ceremony inmany applications. Only one file in the application may use top-levelstatements.

We don't need to use the Main method as a starting point and the code does not have to be placed inside an application class.

In this tutorial, much of the code will be written in top-level statements.

C# console reading values

We can use the Console class to read values as well.

Program.cs

The second program reads a value from a console and prints it.

We read a line from the terminal. When we hit the Enter key, theinput is assigned to the name variable. The input is stored into thename variable, which is declared to be of type string.

In this code line, we do string formatting. The {name} specifieris replaced with the value of the name variable.

C# command line arguments

C# programs can receive command line arguments. They follow the name of theprogram, when we run it. A C# program receives command line arguments in the args array of strings.

Command line arguments can be passed to the Mainmethod.

We go through the array of these arguments with a for loop and print themto the console. The Length property gives the number of elementsin the array. Loops and arrays will be described in more detail later.

We provide three numbers as command line arguments and these are printed to theconsole.

C# variables

A variable is a place to store data. A variable has a name and a datatype. A data type determines what values can be assigned to the variable, forinstance integers, strings, or boolean values. Over the time of the programvariables can obtain various values of the same data type. Variables are alwaysinitialized to the default value of their type before any reference to thevariable can be made.

Program.cs

In the example we have four variables.

We declare a city variable of the string type andinitialize it to the 'New York' value.

We declare and initialize two more variables. We can put two statementson one line. But for readability reasons, each statement should be ona separate line.

We print the values of the variables to the terminal.

101 Visual Basic And C# Code Samples

We assign a new value to the city variable.

The var keyword

Variables at a method scope can be implicitly typed using the varkeyword. The variables are always strongly types, but with varthe type is inferred by C# compiler from the right side of the assignment.

Program.cs

In the program we have two implicitly typed variables.

On the left side of the assignment we use the var keyword.The name variable is of string type and theage of int. The types are inferred from the right sideof the assignment.

We determine the types of the variables with GetType.

This is the output.

C# List collection

While variables hold single values, multiple values can be added tocollections. A List is a sequence of elements, whichcan be accessed by indexing operation with [].Elements of a list can be traversed with e.g. a foreachkeyword.

In the example, we work a list of words.

In order to work with a List, we need to import the System.Collections.Generic namespace.

A list object is created with the new keyword. Between the anglebrackets <> we specify the data type of the list elements.The list is initialized with elements inside the curly brackets {}.

Here we print the third element to the console. (The indexes start from 0.)

Using a foreach loop, we go through all elements of the listand print them to the console. In each of the cycles, theword variable is given one of the elements from the list.

C# discards

Discards are special, write-only variables which are used to trash thevalues that are not interesting to the programmer. The _(underscore character) is used for a discard.

Program.cs

The example defines a tuple of values. By using a deconstruction operation, weassign the values of the tuples into variables.

We define a tuple of six values. A tuple is a collection of ordered,heterogeneous elements.

Say, we are interested only in the first three values of the tuple. On the leftside of the assignment, we define three variables: x,y, and y. Since the vals tuple has sixelements, we need to have six variables on the left side as well. Here we canuse the _ character for the remainding variables. This way weindicate that currently these values are not important to us an we won't workwith them.

C# Range method

The Range method generates a sequence of numbers within a specifiedrange. The first parameter is the value of the first integer in the sequence.The second parameter is the number of sequential integers to generate.

The example prints values 1..10 to the terminal using a foreach loop.The sequence of the integers were generated with the Rangemethod.

101 Visual Basic And C# Code Samples

We get the Enumerable.Range from System.Linq.

C# constants

Unlike variables, constants retain their values. Onceinitialized, they cannot be modified. Constants are created withthe const keyword.

Program.cs

In this example, we declare two constants and one variable.

We use the const keyword to inform the compiler that we declare aconstant. It is a convention to write constants in upper case letters.

We declare and initialize a variable. Later, we assign a new value to thevariable.

This is not possible with a constant. If we uncomment this line, we get acompilation error.

C# string formatting

Building strings from variables is a very common task in programming.C# has the string.Format method to format strings.

Strings are immutable in C#. We cannot modify an existing string. We must createa new string from existing strings and other types. In the code example, wecreate a new string. We also use values from two variables.

Here we define two variables.

We use the Format method of the built-in string class. The{0}, {1} are the places where the variables areevaluated. The numbers represent the position of the variable. The{0} evaluates to the first supplied variable and the{1} to the second.

C# string interpolation

Some dynamic languages like Perl, PHP or Ruby support string/variableinterpolation. Variable interpolation is replacing variables with their valuesinside string literals. C# supports variable interpolation since C# 6.0.

Program.cs

In the code example, we build a string using variable interpolation.

The string is preceded with the $ character and the variablesare inside curly brackets.

This chapter covered some basics of the C# language.

This is one of my favorite question during interview as a part of .NET Framework fundamental, and I generally received very mixed response. Can we have both c# and visual basic project in same solution ?. The response I used to received “No, it is not possible”, “Yes. we can do it for web project” etc. This question comes up when we discuss about very basic of CLS, CTS, MSIL etc. While developers having understanding with these terminologies, most of them failed to understand this basic question which actually related to them.

All right! So, what is the answer ? – Of Course ! Why not ? We can have a Solution, with different types of languages and they can refer. Just like a another reference library; in fact it could be any other language supported by the Framework. When they compiles, all the languages uses their native Compiler ( C# –> CSC Compiler, VB –> VB Compiler ) to generates the IL and that is understandable by other languages.

Here is one simple walkthrough on using this..

101 Visual Basic And C# Code Samples Download

  1. Run a new instance of Visual Studio
  2. Create a new C# Console Application Project.
  3. Add a new “Visual Basic Project” using “Add New Project” dialog window”
  4. Add the VB Class Library Project as Reference to C# Project.

This is how the solution should look like:

Now, you can write some dummy code block , one method that write something on console, and one method to add two number.

Here is the C# Code block, that calls the above VB methods which included as part of reference assembly.

Once you run the application, this is how your output will come.

The application execution code map would look like as below.

To take an inside look, if you open both the VB Library, C# Code using ILDASM,now; you should be able to relate how IL code is getting called with same data type over different language.

101 Visual Basic And C# Code Samples Pdf

Hope this will give you a good understanding.

How To Code Visual Basic

How To Do it for ASP.NET Web Application ?A Beginner’s Guide to ASP.NET Application Folders