Getting to know Windows Presentation Foundation (or WPF)

Until now,we were making Console Applications (output coming up on the black console window). Now let’s move ahead and explore WPF (Windows presentation Foundation).

Create a project and you can see multiple files created by Visual Studio itself. You can see the file list in Solution Explorer.

In addition to C#, we will need to learn some XAML here. XAML is a markup language something similar to HTML. We will go to that later.

You will have the following files in addition to other files

MainWindow.xaml  (This is your interface which will have many wpf controls)

MainWindow.xaml.cs (This is where your code should be)

App.xaml

App.xaml.cs

Now you write your code.

I’m Learning C# – Part 11

In this lesson, we are going to use enum and switch together.

class Program
{
static void Main(string[] args)
{
List<doc> DocList = new List<doc>()
{
new doc {name =”first”, status = testStatus.Created, number= 1},
new doc {name =”second”, status = testStatus.Review, number= 2},
new doc {name =”third”, status = testStatus.Approval, number= 4},
new doc {name =”forth”, status = testStatus.Released, number= 4},
new doc {name =”fifth”, status = testStatus.Obsolete, number= 5},
};
foreach (var item in DocList)
{
switch (item.status)
{
case testStatus.Created:
Console.ForegroundColor = ConsoleColor.White;
break;
case testStatus.Review:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case testStatus.Approval:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
case testStatus.Released:
Console.ForegroundColor = ConsoleColor.Green;
break;
case testStatus.Obsolete:
Console.ForegroundColor = ConsoleColor.Red;
break;
default:
break;
}
Console.WriteLine(“the name is {0} and status is {1}”, item.name, item.status);

}
Console.ReadLine();
}
}

class doc
{
public string name {get; set;}
public testStatus status {get; set;}
public int number {get; set;}
}

public enum testStatus
{
Created,
Review,
Approval,
Released,
Obsolete
}

Enum is used when we want to restrict the values that a particular parameter can take. In this case, we want to limit the status to Created, Review, Approval, Released or Obsolete.

The switch, depending on the status, changes the ForegroundColour of the console as can be seen in the output below:

capture

Isn’t that lovely 🙂

What if we encounter an exception during run time?

In that instance, we make use of the try catch block.

try
{
var content = File.ReadAllText(@”C:\google.txt”);
Console.WriteLine(content);
}
catch(FileNotFoundException e)
{
Console.Write(e.Message);
}
Console.ReadLine();

With this post, I am pretty much wrapping up the C# sessions.

Do comment on areas I haven’t covered and maybe I will write another post 🙂

I’m Learning C# – Part 10

The following is a code to determine how many days have passed since I was born.

DateTime current = DateTime.Now;
DateTime myBirthday = DateTime.Parse(“1900, 01, 13”);
TimeSpan today = current.Subtract(myBirthday);
Console.WriteLine(today);

or

DateTime today1 = DateTime.Now;
DateTime birthday = DateTime.Parse(“1900,01,31”);
TimeSpan interval = today1 – birthday;
Console.WriteLine(interval);
Console.ReadLine();

We are using DateTime which is part of a struct. Again we are using TimeSpan which is part of another struct. You don’t need to by heart all these. Highlight the term you want to know about, clikc F12, it will take you to the definition of that term in Reference Source.

Now a little about the static keyword.

I have a class car which has a method price1() which is static.

class car
{
public int number { get; set; }
public string colour { get; set; }
public string make { get; set; }

public static double price1()
{
double value = 1;
return value;
}
}

To access this method inside my main method, all I have to do is

Console.WriteLine(“{0}”,car.price1());
Console.ReadLine();

Instead if I didn’t have the static word, I would have had to create an instance of car (an object) and use it access the method.

class car
{
public int number { get; set; }
public string colour { get; set; }
public string make { get; set; }

public double price1()
{
double value = 1;
return value;
}
}

Then my code in main() should be

car myCar = new car();
Console.WriteLine(“{0}”,myCar.price1());
Console.ReadLine();

See the difference 🙂

There are different ways to initialize the number, colour and make of the car.

car myCar = new car();
myCar.number = 8123;
myCar.make = “Maruti”;
myCar.colour = “Black”;

or

car myCar2 = new car() { number = 123, make = “jazz”, colour = “white” };

Now to manually delete an object you created, set it’s value to null

myCar2 = null;

The .Net Framework has a garbage collector which will remove all references to memory once the object life is completed or out of scope.

The following is how to define a List and intialize values to it. List is found in System.Collections.Generic so you need to add it in the using.

List<car> List1 = new List<car>()
{ new car(){ number = 1223, make = “honda”, colour = “yellow” } };

I’m Learning C# – Part 9

The best way to learn or I must say use a blend of loops is by creating patterns. Here I made a diamond of “*”. Try for yourself

class Programcapture
{
static void Main(string[] args)
{

StringBuilder newstring = new StringBuilder();
for (int i = 0; i <= 10; i++)
{
int k = i;
while(k<10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2*i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
for (int i = 9; i >= 0; i–)
{
int k = i;
while (k < 10)
{
newstring = newstring.Append(” “);
k++;
}

for (int j = 0; j <= 2 * i; j++)
{
newstring = newstring.Append(“*”);
}
newstring = newstring.Append(“\n”);

}
Console.WriteLine(newstring);
Console.ReadLine();
}
}

Changing the numbers here and there and playing with the loops will get you many more patterns 🙂

Things which are new here is StringBuilder. It’s a class included in System.Text and it is sealed class which means you cannot inherit it. Now we have created an object of the type StringBuilder called ‘newstring’ to do our appending. Now this method will be effective when we have lot of appending to be done to reduce the strain on memory.

I’m Learning C# – Part 8

Today we will learn how to reverse a string.

Method 1: read from console into a string, assign it into a character array, use the reverse property of arrays and then write it to console.

string straight = Console.ReadLine();
char[] charnew = straight.ToCharArray();
Array.Reverse(charnew);
Console.Write(charnew);
Console.ReadLine();

Method 2: Assigning the reversed data read from the console and assigning it to the char array.

char[] charnew = Console.ReadLine().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Converting to upper case along with reversal

char[] charnew = Console.ReadLine().ToUpper().Reverse().ToArray();
Console.Write(charnew);
Console.ReadLine();

Next let us learn to generate a random number. So this is a simple code which takes in any name and prints a random number between 1 and 50 as the age of the person.

class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name,age(name));
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random(); // Random is the class and we are creating an object randomAge here
int rand = randomAge.Next(1, 50); // Next is a method defined in the class Random
return rand;
}
}

Now if we want a do-while loop for the above logic, lets try something like this

class Program
{
static void Main(string[] args)
{
bool x = true;
do
{
Console.WriteLine(“Enter the name”);
string name = Console.ReadLine();
Console.WriteLine(“the age of {0} is {1}”, name, age(name));
Console.WriteLine(“do you want to continue? 1 for yes; 0 for no”);
string response = Console.ReadLine();
if (int.Parse(response) == 1)
{
x = true;
Console.WriteLine(“continuing the loop”);
}
else
{
x = false;
Console.WriteLine(“exiting the loop”);
}

} while (x);
Console.ReadLine();
}
static int age(string name)
{
Random randomAge = new Random();
int rand = randomAge.Next(1, 50);
return rand;
}
}

I’m Learning C# – Part 7

It’s a long time since our last post on learning C#. So I thought to use this post as some kind of a refresher with some additional inputs.

Remember in the beginning of each code, we have used using System; Now System is a namespace which contains Console.WriteLine and Console.ReadLine that we used later in our code. So if we do not have the same first line, we could also use System.Console.WriteLine and System.Console.ReadLine instead. Console is a class inside System and WriteLine and ReadLine are methods inside them. Curious to know more – check out this link. Your namespace ensures that whatever methods, classes, variables you create inside of it, doesn’t meddle with other namespaces anywhere else. That’s the importance of having your own namespace, organizes things.

  1. Okay, now ever wondered what to do if you forgot the syntax of a loop, say for loop. Very simple, just type in for then click tab twice. Visual studio will do automatic filling for you 🙂 
  2. For debugging, use F5, F9, F10, F11.
  3. Declare variables as and when you need them. Don’t list everything on the top.
  4. Your machine code is found inside the bin folder -> debug of your project.

A small bit of an array snippet so that we stick to coding.

int[] array = new int[5]; // this is the array declaration
for (int i = 0; i < array.Length; i++) // length of the array is 5
{
array[i] = 2 * i;
Console.WriteLine(array[i]);

}
Console.ReadLine();

Now 2 ways to loop through the elements of an int array and a string array are given below:

int[] array = new int[] { 1,2,3,4,5};
for (int i = 0; i < array.Length; i++)
{
array[i] = 2 * i;
Console.WriteLine(array[i]);

}
foreach (int item in array)
{
Console.WriteLine(item);
}

string[] str = new string[] { “hi”, “hello”, “3”, “ok” };
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine(str[i]);
}

foreach (string item in str)
{
Console.WriteLine(item);
}
Console.ReadLine();

We can make use of a simple for loop or we could you a foreach loop

I’m Learning C# – Part 6

Today we will study about methods or functions. We already know one method which is main (). In the statement, static void main (string [] args), main is the name of the function that returns nothing or void. 

How does a method work? First we need to define a method with the return type if any and also mention the arguments that will be passed to that method. Then we need to call the method from our program. The advantage of this is we can call the method any number of times without having to actually repeat the lines of code over and over.

The following is a code that makes use of method ‘area’ to calculate and print the area of a circle when the radius is inputted.

static double area (double x)
{
return 3.14 * x * x;

}
static void Main (string [] args)
{
Console.WriteLine(“enter the number”);
double num = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(“The area is {0}”, area(num));
}

If you have issues with remembering the order in which the arguments are defined in the methods, during passing you can name the arguments in the style given below:

static int volume (int x, int y, int z)
{
return x*y*z;

}
static void Main (string [] args)
{
int x, y, z;
Console.WriteLine(“The volume is {0}”, volume(x:4, z:5, y:2));
}

In these examples even though the parameters where passed to method and operations were performed on them, the actual values of the parameters remain the same. This is called ‘ call by value’.

static void num (ref int y)
{
y /= 2; ;

}
static void Main (string [] args)
{
int x = 10;
num(ref x);
Console.WriteLine(“x is {0} – call by reference”, x);
}

In call by reference, you are actually not making a copy of the parameter being passed but passing the memory location which means any operation you do in the method on the parameter will be stored in the same memory location itself. In the above case, the output will not be 10 but 5. Remember the ‘ref’ keyword is required in the method and while calling.

static void num (out int y)
{
y = 2;

}
static void Main (string [] args)
{
int x;
num(out x);
Console.WriteLine(“x is {0} – call by output”, x);
}

You use the out keyword when you want to pass value from the method to the main function. In this case, output is 2 which is nothing but the value of y passed into x through the out.

In the following code we use method overloading which means methods that have same name but only differ in the arguments.

static int sum (int x, int y)
{
return x+y;

}
static int sum(ref int x, ref int y)
{
x += 5;
y *= 2;
return x + y;

}
static int sum1(out int x, out int y)
{
x = 9;
y = 10;
return x + y;

}
static void Main (string [] args)
{
int x = 1, y = 2;
Console.WriteLine(“x is {0} y is {1} and returned values is {2}”, x,y,sum(y:3,x:5)); // x is 1 y is 2 and returned values is 8
sum(ref y, ref x);
Console.WriteLine(“x is {0} y is {1}”, x, y); //x is 2 y is 7
sum1(out y, out x);
Console.WriteLine(“x is {0} y is {1}”, x, y);//x is 10 y is 9
}

I’m Learning C# – Part 5

In the precious post, we had used if, else if and else in the code for for loop.  What it does is it states under this condition, you execute the following statements.

Another similar statement is the switch.

We are using the same code used for fibo nacci series

static void Main(string[] args)
{

Console.WriteLine(“enter the number of Fibonacci numbers required”);
int x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 0: Console.WriteLine(“no numbers are printed”);
break;
case 1: Console.WriteLine(“The number is 0”); ;
break;
case 2: Console.WriteLine(“The numbers are 0 1 “);
break;
case 3: Console.Write(“The numbers are 0 1 1 “);
break;
default:
{
int y = 1;
int z = 1;
int sum = 0;
Console.Write(“The numbers are 0 1 1 “);
for (; x > 3; x -= 1)
{
sum = y + z;
Console.Write(” {0} “, sum);
z = y;
y = sum;

}
break;
}
}

}

We need to know what break is. Break is used to break free from the current execution statement and move on to the next. So if the break statement is found inside a loop, the execution inside the loop gets terminated and any remaining code outside the loop is executed next.

Another important terminology is continue. Continue skips just the current iteration of a loop but resumes with the rest of the loop iteration.

Now some logical operators:

&& – AND  (LHS and RHS should be True for the condition to be True)

|| – OR (either LHS or RHS should be True for the condition to be True)

! – NOT (works on single operand; if operand is false, the condition is True and vice versa)

I’m Learning C# – Part 4

Today we will be learning about loops. What does a loop do? Suppose we want to add the number 2 to 10, 4 times. So instead of writing 10+2+2+2+2 we go in for a loop where we show the action once and indicate that it has to be repeated.

While loop

Now here is a code which uses the while loop. It will keep on asking to “enter the number” until you enter the value 10 at which the while loop will exist. Only if the condition while(True) does the loop get executed.

static void Main (string [] args)
{
int x = 0;
while (x != 10)
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
}
}

Another loop is the do – while. It’s working is similar to while loop with one difference. The loop will be entered atleast once before the while(True) check is carried out.

static void Main(string[] args)
{
int x = 0;
do
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
} while (x != 10);
}

The same code above is implemented using a for loop below:

static void Main (string [] args)
{
int x = 0;
for (;x!=10;)
{
Console.WriteLine(“enter the number”);
x = Convert.ToInt32(Console.ReadLine());
}
}

Basically a for loop will constitute of 3 parts – initialization, condition and then the increment.

Let’s write a code which will print the fibonacci series

static void Main(string[] args)
{

Console.WriteLine(“enter the number of Fibonacci numbers required”);
int x = Convert.ToInt32(Console.ReadLine());
if (x == 0) Console.WriteLine(“no numbers are printed”);
else if (x == 1) Console.WriteLine(“The number is 0”);
else if (x == 2) Console.WriteLine(“The numbers are 0 1 “);
else if (x == 3) Console.Write(“The numbers are 0 1 1 “);
else
{
int y = 1;
int z = 1;
int sum = 0;
Console.Write(“The numbers are 0 1 1 “);
for (; x > 3; x -= 1)
{
sum = y + z;
Console.Write(” {0} “, sum);
z = y;
y = sum;

}
}
}

We have skipped the initialization part in this code because we already have the value of x from the console.

We can skip initialization and the increment part but the following is an infinite loop.

static void Main(string[] args)
{
for (;;);
}

I’m Learning C# – Part 3

Arithmetic operations – +, , *, /, %

Following is a code which will read in 2 numbers from the console and perform subtraction operation between them. Similar concept can be expanded to other operators.

int x;
int y;
Console.WriteLine(“Enter the numbers”);
x = Convert.ToInt16(Console.ReadLine());
y = Convert.ToInt16(Console.ReadLine());
Console.WriteLine(“difference = {0}”, x-y);

Main thing to remember is that ReadLine takes in only string. So it is required to convert it into the required data type by using the Convert.To<>.

If there are multiple operators in an equation, follow BODMAS.

x +=5; //This is same as x=x+5   This is a form of shorthand.

x++; //Same as x=x+1

++x and x++ are 2 different things. The first one increases the value of x then and there, the other one only in the next iteration.

int x=4; y= x++; //y =4, x= 5

int x=4; y=++x; //y = 5, x=5