Part 1 - C# Tutorial - Introduction: // Namespace Declaration
Part 1 - C# Tutorial - Introduction: // Namespace Declaration
In this session
1. We will learn the basic structure of a c# program. The program we used in this video is shown
below.
// Namespace Declaration
using System;
class Pragim
{
public static void Main()
{
// Write to console
Console.WriteLine ("Welcome to PRAGIM Technologies!");
}
}
2. Understand the purpose of using System declaration - The namespace declaration, using
System, indicates that you are using the System namespace. If you omit the using System,
declaration, then you have to use the fully qualified name of the Console class. A namespace is
used to organize your code and is collection of classes, interfaces, structs, enums and
delegates. We will discuss about namespaces in detail in a later session.
3. Purpose of Main() method - Main method is the entry point into your application.
Verbatim literals make escape sequences translate as normal printable characters to enhance
readability.
Practical Example:
Without Verbatim Literal : “C:\\Pragim\\DotNet\\Training\\Csharp” – Less Readable
With Verbatim Literal : @“C:\Pragim\DotNet\Training\Csharp” – Better Readable
// C# verbatim literal
Name = @"c:\Pragim\DotNet\Training\Csharp";
Console.WriteLine(Name);
}
}
}
In this video, we will discuss the common operators that are available in c# programming
language.
Assignment Operator =
Arithmetic Operators like +,-,*,/,%
Comparison Operators like ==, !=,>, >=, <, <=
Conditional Operators like &&, ||
Ternary Operator ?:
Null Coalescing Operator ??
Examples used in the demo
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
// Assignment Operator example
// Single = is the assignment operator
int i = 10;
bool b = true;
The example below is not using the ternary operator. Look at the amount of code we have
to write to check if a number is equal to 10, and then initialise a boolean variable to true or false
depending on whether the number is equal to 10 or not.
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
int number = 10;
bool isNumber10;
if (number == 10)
{
isNumber10 = true;
}
else
{
isNumber10 = false;
}
Ternary operator example : We have rewritten the above program using ternary operator.
Notice the amount of code we have to write is greatly reduced.
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
int number = 10;
Nullable types bridge the differences between C# types and Database types
if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}
Where as when converting a float to an int, we loose the fractional part and also a possibility of
overflow exception. Hence, in this case an explicit conversion is required. For explicit
conversion we can use cast operator or the convert class in c#.
Console.WriteLine(f);
}
}
Console.WriteLine(i);
}
}
using System;
class Program
{
public static void Main()
{
// Initialize and assign values in different lines
int[] EvenNumbers = new int[3];
EvenNumbers[0] = 0;
EvenNumbers[1] = 2;
EvenNumbers[2] = 4;
// Initialize and assign values in the same line
int[] OddNumbers = { 1, 3, 5};
Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to
store or retrieve items from the array.
Note: Don't try to comment every line of code. Use comments only for blocks or lines of code
that are difficult to understand
Part 10 - C# Tutorial - If statement
The signature of the delegate must match the signature of the function, the delegate points to,
otherwise you get a compiler error. This is the reason delegates are called as type safe function
pointers.
A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass
in the function name as a parameter to the delegate constructor, and it is to this function the
delegate will point to.
Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a
delegate keyword.
using System;
// Delegate Declaration.
public delegate void HelloFunctionDelegate(string Message);
class Pragim
{
public static void Main()
{
// Create the instance of the delegate and pass in the function
// name as the parameter to the constructor. The passed in
// function signature must match the signature of the delegate
HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
// Invoke the delegate, which will invoke the method
del("Hello from Delegte");
}
Approach 1:
using System;
namespace Sample
{
public delegate void SampleDelegate();
Approach 2:
using System;
namespace Sample
{
public delegate void SampleDelegate();
del();
}
Note: A multicast delegate, invokes the methods in the invocation list, in the same order in
which they are added.
If the delegate has a return type other than void and if the delegate is a multicast
delegate, only the value of the last invoked method will be returned. Along the same
lines, if the delegate has an out parameter, the value of the output parameter, will be the
value assigned by the last method.
Where do you use multicast delegates? This is a very common interview question.
Answer: Multicast delegate makes implementation of observer design pattern very simple.
Observer pattern is also called as publish/subscribe pattern.
Examples:
Trying to read from a file that does not exist, throws FileNotFoundException.
Trying to read from a database table that does not exist, throws a SqlException.
Showing actual unhandled exceptions to the end user is bad for two reasons
1. Users will be annoyed as they are cryptic and does not make much sense to the end users.
2. Exceptions contain information, that can be used for hacking into your application
using System;
using System.IO;
class ExceptionHandling
{
public static void Main()
{
StreamReader streamReader = null;
try
{
// This line will throw FileNotFoundException
streamReader = new StreamReader("C:\\NonExistingFile.txt");
Console.WriteLine(streamReader.ReadToEnd());
}
// This catch block handles only FileNotFoundException
catch (FileNotFoundException fileNotFoundException)
{
// Log or email the exception
// Code to log or email exception details
Specific exceptions will be caught before the base general exception, so specific exception
blocks should always be on top of the base exception block. Otherwise, you will encounter a
compiler error.
Note: It is a good practice to always release resources in the finally block, because finally block
is guarenteed to execute, irrespective of whether there is an exception or not.
To look at the inner exception, you have to make this program cuase an exception fail. To do
that you have 3 options
1. Enter a Character instead of a number (Causes Format Exception)
2. Or Enter a very big number that an interger cannot hold (Causes Over Flow Exception)
3. Or Enter Zero for Second Number (Causes Divide By Zero Exception)
using System;
using System.IO;
class ExceptionHandling
{
public static void Main()
{
try
{
try
{
Console.WriteLine("Enter First Number");
int FN = Convert.ToInt32(Console.ReadLine());
Consider that
1. I have an asp.net web application.
2. The application should allow the user to have only one logged in session.
3. If the user is already logged in, and if he opens another browser window and tries to login
again, the application should throw an error stating he is already logged in another browser
window.
With in the .NET framework we donot have any exception, that adequately describes this
problem. So this scenario is one of the examples where you want to create a custom exception.
We know that an exception is a class. So to create a Custom exception,
1. Create a class that derives from System.Exception class. As a convention, end the
class name with Exception suffix. All .NET exceptions end with, exception suffix. If you
don't do so, you won't get a compiler error, but you will be deviating from the guidelines
for creating custom exceptions.
public class UserAlreadyLoggedInException : Exception
{
}
2. Provide a public constructor, that takes in a string parameter. This constructor simply
passes the string parameter, to the base exception class constructor.
public UserAlreadyLoggedInException(string message)
: base(message)
{
}
3. Using InnerExceptions, you can also track back the original exception. If you want to
provide this capability for your custom exception class, then overload the constructor as
shown below. If you are new to Constructor Overloading, please watch this video.
public UserAlreadyLoggedInException(string message, Exception innerException)
: base(message, innerException)
{
}
4. If you want your Exception class object to work across application domains, then the
object must be serializable. To make your exception class serializable mark it with
Serializable attribute and provide a constructor that invokes the base Exception class
constructor that takes in SerializationInfo and StreamingContext objects as parameters.
[Serializable]
public class UserAlreadyLoggedInException : Exception
{
public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
Note: It is also possible to provide your own custom serialization, which will discuss in a later
session.
Complete Example of creating a custom exception:
using System;
using System.Runtime.Serialization;
[Serializable]
public class UserAlreadyLoggedInException : Exception
{
public UserAlreadyLoggedInException(string message)
: base(message)
{
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Denominator cannot be zero");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}