C# Example of Math Expressions, Variables, and If Statements

Anyone getting into C# and ASP.NET development will likely be starting with basic expressions, variables, and if statements. Get familiar with these concepts:


private void radioButton1_CheckedChanged(object sender, EventArgs e) 
{ 
    string x = this.textBox1.Text; 
    string y = this.textBox2.Text; 
    if (x == "") //See if x has no value 
    { 
        x = "0"; //Set x to 0 
    } 
    if (y == "") //See if x has no value 
    { 
        y = "0"; //Set y to 0 
    } 
    int x_number = Convert.ToInt32(x); //Converts the string x to a number then stores it in x_number 
    int y_number = Convert.ToInt32(y); 
    int random = x_number + y_number; //Sets the integer variable random to the value of x_number plus y_number 
    string random_string = Convert.ToString(random); //Converts the integer random to the string random_string 
    this.label3.Text = random_string; 
}

What Are The C# Access Modifiers

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Creating Hashtables in C#

Creating a Hashtable Object with the Hashtable Class in C#

The hashtable class in C# is used to create a hash table. The syntax to create a new hash table is:

public Hashtable name_of_hashtable = new Hashtable ();

When you create a new hashtable, it is empty. Let’s create a hashtable called hashtableexample and place three integer keys inside it:

using System.Collections;
using System;
class Example
{
    static void Main()
    {
                Hashtable hashtableexample = new Hashtable();
                hashtableexample[1] = "One";
                hashtableexample[3] = "Three";
                hashtableexample[29] = "Twenty-Nine";
                foreach (DictionaryEntry entry in hashtableexample)
                {
                    Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
                }
    }
}
Output:
29: Twenty-Nine
3: Three
1: One

In this program, we have created a class called Example to hold the hashtable named hashtableexample. We added three integer keys to that hashtable, with different entry key numbers and values. The integer keys we added belong to the DictionaryEntry type, which contains keys and their corresponding values. We added three keys with different key entries and values. In the final part of the program, we printed the keys with the corresponding values to the screen using the foreach loop.

It’ll be easier to learn the language as a whole instead of bits and pieces, so we recommend you check out this advanced course in C# to learn more about hashtables.

Adding Entries to a Hash Table

Now that we know how to add keys to a hash table, let’s see how to add entries to it. The syntax to add an item to a hashtable object is:

name_of_hashtable.Add(Parameter 1 (Data), Parameter 2 (Data))

You’d understand the syntax better with an example program. We’ll write a simple hashtable that contains the name of three authors and the number of books they’ve sold recently:

using System.Collections;
using System;
class Example
{
    static void main()
    {
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRownling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);
    }
}

We created a simple hashtable with three entries inside it. As you can see, we used string values as well as integer values. Both your entries could have contained string or integer values. You can try writing the hashtable to the screen to see what it looks like (using the foreach loop, as we showed you earlier).

Hashtable Methods

There are several methods that you can use with the hashtable class. The Add method, for example, adds an entry to the hashtable class (like in the program above), the Clear method can be used to wipe the hashtable clean, the Clone method creates a copy (shallow) of your hashtable and the GetHash method returns the hashcode for a specific key. You will need to get familiar with most of the hashtable methods if you’re going to get a good grasp on hashtables and handle them properly. You can check out the different methods in the official documentation on the Microsoft Office website. Learn more about these methods in detail with this C# course.

We’ll write a simple program that demonstrates the use of the Contains method to help you understand the concept better. We’ll just extend the program we wrote earlier:

using System.Collections;
using System;
class Example
{
static Hashtable GetHashtable()
    {
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRowling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);
                return hashtableexample;
   }
static void Main ()
{
Hashtable hashtableexample = GetHashtable ();
Console.WriteLine(hashtableexample.Contains (“JKRowling”));
}
Output:
True

The Contains method checks the hash table to see if a specific key is present. If it is, it will return a true value. If not, it returns a false value. We created a simple hash table called hashtableexample and then returned its value. We then checked to see if any of the keys in the hash table match “JKRowling” with the Contains method.

C# also has a newer, much more efficient class called the Dictionary collection which is quite similar in functionality. If you’re going to operate or maintain one of those programs for a company, you need to know about the hashtable class. The .NET framework makes C# sharp portable and platform independent, just like Java.  There is a growing demand for C# programmers in the industry and a shortage of good programmers. You may want to explore C# programming as a career option. This three part course gets into the details of C#(Part I, Part II, Part III) – from the basics to the advanced concepts – to help you along your journey.

C# Basic Code Elements

Variables and different types.

C# is a static-typed language therefore we must define the variable type for the system to recognize it.

//Here is an example of the 6 kinds of variable types you can use
int anIntenger = 1;
float floatingNumber = 1f;
bool booleanValue = true;
string aString = "John";
char aSingleCharacter = 'a';
double usingDecimals = 1.75;
//Note, the float variable always has an f at the end of it.


using System;
public class Tutorial
{
   public static void Main()
   {
      string productName = "TV";
      int productYear = 2012;
      double productPrice = 279.99; 

      Console.WriteLine("productName: " + productName);
      Console.WriteLine("productYear: " + productYear);
      Console.WriteLine("productPrice: $" + productPrice);
   }
}

Examples of how arrays work in C#

using System;
public class Tutorial
{
   public static void Main()
   {
       string[] fruits = {"apple", "banana", "orange"};

      Console.WriteLine(fruits[0]);
      Console.WriteLine(fruits[1]);
      Console.WriteLine(fruits[2]);
   }
}

Using lists in C#

Here is a list where we added some prime numbers.

using System;
using System.Collections.Generic;

public class Hello
{
    public static void Main()
    {
        List<int> primeNumbers = new List<int>();
        primeNumbers.Add(2);
        primeNumbers.Add(3);
        primeNumbers.Add(5);
        primeNumbers.Add(7);
        primeNumbers.Add(11);

        Console.WriteLine(primeNumbers.Count);
        Console.WriteLine(primeNumbers[0]);
        Console.WriteLine(primeNumbers[1]);
        Console.WriteLine(primeNumbers[2]);
        Console.WriteLine(primeNumbers[3]);
        Console.WriteLine(primeNumbers[4]);
    }
}

Using the Dictionary list

Dictionaries are special lists, whereas every value in the list has a key which is also a variable.

using System;
using System.Collections.Generic;

public class Hello
{
    public static void Main()
    {
        Dictionary<string, int> inventory = new Dictionary<string, long>();
        inventory.Add("apple", 3);
        intentory.Add("orange", 5);
        inventory.Add("banana", 2);

        Console.WriteLine(inventory["apple"]);
        Console.WriteLine(inventory["orange"]);
        Console.WriteLine(inventory["banana"]);
        
        //Another example of using Dictionary for a phonebook
        Dictionary<string, long> phonebook = new Dictionary<string, long>();
		phonebook.Add("Alex", 415434543);
		phonebook["Jessica"] = 415984588;

		phonebook.Remove("Jessica");
		Console.WriteLine(phonebook.Count);
    }
}

Strings

Combining elements together into a string.

string fruit = "apple,orange,banana";
Console.WriteLine("Found orange in position: " + fruit.IndexOf("orange"));
Console.WriteLine("Found lemon in position: " + fruit.IndexOf("lemon"));