Easy C#

Data structures, Ternary operator, Default parameterers... There's enough to keep you geekin.

Posted by Rishi Raj Gujadhur 1/13/2016


Table of content

 

Prerequisites

 
  • You need to be a c# apprentice. You can learn more about the apprentice c# course using the following link: Apprentice_C#
 
  • The software, Microsoft Visual Studio 2010,2012, 2013 Windows Express or Ultimate is required.
 

A. Creating a console application


1. Go to:

Files > New > Projects > Visual C#

2. Select Console application 

Name the application: "EasyCSharp" as shown in the diagram below:



3. Click OK.

Modifying the console application

1. Open program.cs

2.Inside the Main event static void Main(string[] args){ }​ Type:

Console.Writeline("Hello World");
 
Writeline("Hello World") ----> Just like the MessageBox which we looked at in the aprentice c# course, the writeline method takes a string or character as parameter and displays it on the console application. 

Console.ReadLine(); 
 
ReadLine() ----> The readline method is used to tell the console application that there is a line that it should read before exiting. 

Notice that both the Readline and the writeline methods are situated in the Console class and thus in order to access the console class method we need to include the Console. keyword.

3. Press F5 or Fn + F5 to execute the application.

Result: 
 

B. Switch Statements


Just like the if/else statement that we looked at in the previous c# tutorial series; the switch statements are used to evaluate the values using conditions.

1. Type:

 int number = 1;

            switch (number)
            {

                case 2:
                    Console.WriteLine(2);
                    break;

                case 1:
                    Console.WriteLine(1);
                    break;

                default:
                Console.WriteLine("Neither 1 nor 2");
                break;     

            }

 
switch (number) ----> The switch keyword is followed by the value to be evaluated enclosed in parenteses.

case 2:  Console.WriteLine(2); ----> in case the variable "number"'s value is 2 then write 2 on the console.

break; ----> The break keyword is utilize to end the switch statement in case the value evaluates to true.

default: -----> the default keyword represent the statement to executes if all other statements enclosed by switch keyword evaluates to false.

Hints:

Do not forget to use the Console.Readline() keywords.

Make sure place the code in the Main event as we done before. when we created the console application. 

Quick tip: You can evaluate multiple values at once if the same message is to be displayed for each of them as shown below.
                
                case 3:
                case 5:
                    Console.WriteLine("3 or 5");
                    break;

2. Execute the application.

Result: 1
 

C. Ternary Operator




1. Type:

int value =2;

Console.WriteLine(value == 2 ? "The value is 2" : "The value is 1");

 
value == 2 ? "The value is 2" ----> if the value is 2 then output "The value is unknown" 

: "The value is unknown"  ----> the : keyword is used to add to dafault output which would occur in case the condition is not meet.

2. Execute the application.
 

D. Array




1. Type

int[] myArray = new int[5] { 1, 2, 3, 4, 5 };
 
int[] ----> The square brackets [] tells the system that we are declaring an array.

new ----> The new keyword is specified to ensure that each value of the array has its own new index to which we can point to once the value is added.

int[5] ----> The size of the array is 5; thus it can only contain 5 digits and not 5 strings since the array's datatype has been declared as int.

2. To access the array values, type:

Console.Writeline(myArray[1].ToString());
 
myArray[1] ----> the array's name is followed by square brackets [ ] in which the value's index is specified.

An array's index always starts by 0 thus if we want to access the first value of the array then the number 0 needs to be specified.

2.Execute the application.

Result: 1
 

E. List




1. Type: 

List<int> myList = new List<int>();
 
<int> ----> the <> sign needs to be specified to tell the system that we are using a list.

() ----> the list can take no parameter.

myList.Add(1);
myList.Add(2);
myList.Add(3);

 
.Add(1) ---->The Add method is used to add a new value to the list, notice that the method takes the value to be added as parameter.

Also the data type of the value to be a added depends on list 's datatype which is specified by the user on the declaration of the list.  

Console.WriteLine(myList[0]);
 
myList[0] ----> Just like the array the list's value can be accessed using its index.

2. Execute the application.

Result: 1
 

F. Dictionary 




1. Type:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
 
<string, string> ----> the dictionary takes 2 datatypes; the first one is for the index. Can you guess what the second one is used for? :)

myDictionary.Add("P@ssOrd007", "Important information");
 
.Add("P@ssOrd007", "Important information") ----> The dictionary requires an index value and a value for your content which the index can point to.

Console.WriteLine(myDictionary["P@ssOrd007"]);
 
myDictionary["P@ssOrd007"] ----> The dictionary's values can be accessed using specified indexes.

2. Execute the applicaiton.

Result: Important information
 

G. Foreach Loop




1. Type:

int[] myArray = new int[5] {1,2,3,4,5};

foreach(int item in myArray)
{

       Console.WriteLine(item.ToString());
}

 
foreach(int item in myArray) ----> the foreach keyword is followed by the data type of the array those values we want to access.

(int item in myArray) ----> Notice that the statement following the foreach keyword is enclosed in parenthesis ().

item in myArray ----> the in keyword is followed by name of the array that we want to access. (the values are in the array).

{ Console.WriteLine(item.ToString()); } ----> The statement to execute for each value in the array is enclosed in curly brackets.

item ----> we no longer need to specify the values' index to access them since we are using the foreach loop.

2. Execute the query.

Result: 

1
2
3
4
5
 

H. Datetime




1. Type:

Console.WriteLine(DateTime.Now.Day.ToString());
 
DateTime.Now.Day ----> Returns the current date when it is executed.

Console.WriteLine(DateTime.Now.ToString());
 
DateTime.Now -----> Returns the current date/month/year and time. For example: 1/14/2016 8:27:13 PM.

Console.WriteLine(DateTime.MaxValue.ToString());
 
DateTime.MaxValue ----> Takes you to the future. ;)

Console.WriteLine(DateTime.MinValue.ToString());
 
DateTime.MinValue ----> Takes you to the past.

2. Execute the application.
 

I. Random




1. Type:

Random objRandom = new Random();

Console.WriteLine(objRandom.Next(1, 10));
 
Random objRandom = new Random(); ----> To use the methods present in the Random class; instantiation of a object is required.

objRandom. ----> we access the Random class methods using the instantiated object name followed by the . sign.

objRandom.Next(1, 10) ----> the Next method requires 2 integer values to be used as a range for random values to be generated.

2. Execute the application.
 

J. Substring




1. Type:

Console.WriteLine("Channel R".Substring(8,1));
 
"Channel R".Substring ----> Notice that the to access the Substring method we need specify a string of characters enclosed in double quotes " ". 

(8,1) The Substring method takes 2 integer values as parameters, the 1st one parameter is used to indicate where you want to start cropping your string from.

The 2nd parameter is the length of the string that you want to return.

2. Execute the application.

Result: R
 

K. Default Parameter




1. Type:

public static void myMethod(string firstName, string lastName = "Unknown")
{

            Console.WriteLine("First Name = {0}, Last Name = {1}", firstName, lastName);
}
 
Notice that the static access modifier was used which is beyond the scope of this Easy c# tutorial.

The static access modifier would be covered in the intermediate c# tutorial so you do not need to focus on it in this tutorial. 

(string firstName, string lastName = "Unknown")  ----> Notice that the default parameter needs to be after the non-default parameter "firstName". 

("First Name = {0}, Last Name = {1}", firstName, lastName); ----> the {0} curly brackets containning a digit such as 0 indicates the order in which values from variables will be displayed.

2. Type in the Main Event:

myMethod("Tom"); 

3. Execute the application.


Result: First Name = Tom, Last Name = Unknown
 

L. Property




1. Type:

class ClNumber
        {
            int number;
            public int Number
            {
                get
                {
                    return number;
                }
                set
                {
                    number = value;
                }
            }
        }
 
Shortcut to create a property = prop + 2x tab 

public int Number ----> Notice that a property has no return type.

get { return number; } ----> provides external reading access to the number variable through the property.

set { number = value; } ----> allow overwriting the number variable 's value through the property.

Not including the set { number = value; } keywords in the property would make its value read only.

2. Instantiate the class ClNumber in the Main event:

ClNumber objNumber = new ClNumber();
            objNumber.Number = 1; 
 
objNumber.Number ----> Once the class clNumber's object has been instantiated, just use the class object name followed by .PropertyName to get read/write its value.

            Console.WriteLine(objNumber.Number);

3. Execute the application.

Result: 1
 

M. Struct




Click on the following link to find out about when to use a struct and when to use a class: https://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx

1. In program.cs but outside the Main event, type:

struct myStruct
{
    public int ID;
    public string Name;
};

2. In the Main event, type:

   myStruct objMyStruct;
 
myStruct objMyStruct; ----> Notice that the "new" keyword is not used which is required when using classes. This because the struct is used as a value type, for instance as a string.

 objMyStruct.ID = 1;
 objMyStruct.Name = "James Bond";
 Console.WriteLine(objMyStruct.Name);
 
objMyStruct.Name ----> Accessing the field within a struct is similar to accessing a class fields.

3. Execute the application.
 

N. Next Step

 
  • Feel free to apply all the concepts that we learned about in this tutorial using Microsoft Visual Studio 2010, 2012, 2013 Ultimate or Windows Express.