0% found this document useful (0 votes)
19 views44 pages

C# Beginner Crash Course Guide

This document is a crash course on C#.NET for beginners, covering essential topics such as variables, literals, operators, control flow statements, functions, arrays, and exception handling. It explains the rules for variable declaration, types of operators, and the structure of control flow statements like if-else and loops. Additionally, it discusses exception handling mechanisms in C#, emphasizing the importance of managing runtime errors effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views44 pages

C# Beginner Crash Course Guide

This document is a crash course on C#.NET for beginners, covering essential topics such as variables, literals, operators, control flow statements, functions, arrays, and exception handling. It explains the rules for variable declaration, types of operators, and the structure of control flow statements like if-else and loops. Additionally, it discusses exception handling mechanisms in C#, emphasizing the importance of managing runtime errors effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C#.

NET CRASH COURSE


FOR BEGINNERS

Tools you need to follow along this course:-


Required
MS Visual Studio

Satyarth Programming Hub


VARIABLES, LITERALS,
OPERATORS AND TYPE
CASTING IN C#

C#.NET 2
C#.NET

What is a variable?
• A variable is the name given to any memory location in computer.
• The purpose of the variable is to store some data temporarily.
• The data in a variable can be accessed by using variable name.
• Variable declaration – data_type variable_name;
• Variable initialization – data_type variable_name = value;
• Local Variable – Local Variables in C# are declared inside the method of a class. The scope of the local
variable is limited to the method, which means you cannot access it from outside the method. The
initialization of the local variable is mandatory.
• Class Level Variables
• Non-Static/Instance Variable
• Static Variable
• Constant Variable
• ReadOnly Variable

3
C#.NET

Variable declaration Rules in C#


• A variable name must begin with a letter or underscore.
• Variables in C# are case sensitive. string Name is not same as string name.
• They can be constructed with digits and letters.
• No special symbols are allowed other than underscores.
• TotalSales, Height, _value, and abc123, etc. are some valid examples of the variable name.
• Total@Sales, 12Height, $Value, ect. Are some invalid examples of the variable name.

4
C#.NET

Literals in C#
• Literals in C# are the fixed or hard-coded values assigned to a variable.
• Literal values cannot be modified during the execution of the program.
• Example – int Age = 32; age is a variable and 32 is a literal.
• Example – string name = “Ramesh” name is a variable and “Ramesh” is a literal.
• Literal Types
• Boolean Literals (true & false)
• Character Literals
• Char Literals
• String Literals (Regular & Verbatim Literals)
• Numeric Literals
• Integral Literals
• Floating point Literal

5
C#.NET

Type Casting in C#
• Type Casting or Type Conversion is the process to change one data type value into another data type.
• Type Casting/Conversion is only possible if both the data types are compatible with each other.
• We will get compile time error saying cannot implicitly convert one type to another type.
• Types of Type Casting
• Implicit – Done automatically by the compiler.
• There will be no data loss.
• It is done from a smaller data type to a larger data type.
• This type of type conversion is safe.
• Explicit – Done by using the Cast Operator, Helper Methods and Parse()
• When we want to convert large data type into small data type.
• There could be a data loss.
• Convert class has helper methods to do the conversion from one data type to another.
• string str = “12345”;
• int num = Convert.ToInt32(str);
• int num1 = [Link](str);

6
C#.NET

Operators in C#
• Operators are the symbols that are used to perform certain operations on operands.
• int a = 5, b=20;
• int sum = a + b; a and b are the operands and + is the operator.

• Type of Operators
• Unary – Unary Operators (++, --)
• Binary
• Arithmetic Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Relational Operators
• Ternary – Ternary Operator (?:)

7
GETTING DEEP INTO C#
PROGRAMMING

C#.NET 8
C#.NET

Control Flow Statements


• The Control Flow Statements are used to alter the flow of the program execution.
• Generally, a program executes from top to bottom except when we use control statements. We can control
the order of execution of the program, based on logic and values.
• They provide more control to the programmer on the flow of program execution.
• They are useful to write better and more complex programs.

Control Flow Statements

Iteration Statements Jump Statements


Conditional Statements 1-For 1-Break
1-If, If-Else 2-While 2-Continue
2-Switch - Case 3-Do-while 3-Return
4-foreach 4-Goto

9
C#.NET

If, If-Else
• if(condition)
{
//code goes here.
}

• if(condition)
{
//code goes here.
}
else
{
//code goes here.
}

10
C#.NET

Switch Case
• Switch case statements are a substitute for long if else
statements or if else ladder.
• If we have multiple options, and we must choose only one
from the available options depending on a single
condition then we go for a switch statement.
• Depending on the selected option a particular code will be
executed.

11
C#.NET

While Loop
• While loop is used to execute certain statements repeatedly until a certain condition holds true.

12
Do While Loop
• Do-while loop is a post-tested loop.
• First the loop body will be executed and
then the condition will be checked.
• We should use the do-while loop where we
need to execute the loop body at least
once.

C#.NET 13
C#.NET

For Loop
• For loop is one of the most commonly used loops.
• If we know the number of iterations code needs to be
executed, we should use for loop.
• For loop is known as a Counter loop.
• Whenever counting is involved for repetition, then we can
use for loop.
• It has three main parts
• Initialization
• Condition
• Increment/Decrement
• All three parts are separated by semicolon (;)
14
Break Statement

C#.NET
• Break is a keyword.
• We can terminate loop or switch body by
using break keyword.
• We must put the break keyword inside the
loop body or switch body if we want to break
the execution of the loop/switch.

15
Continue
Statement

C#.NET
• Continue is a keyword.
• we can skip the statement execution
from the loop body by using continue
keyword.

16
C#.NET

Goto Statement
• Goto is a keyword. It can pass the control anywhere in the program in the local scope.
• When we are working with the goto statement it required an identifier called a label.
• Any valid identifier followed by a colon is called a label.
• Whenever we are working with a goto statement it is called an unstructured control flow statement
because it breaks the rule of structure programming language.
• The goto statement is rarely used because it makes the program confusing, less readable, and complex.
• Also, when goto is used, the control of the program won’t be easy to trace, hence it makes testing and
debugging difficult.

17
C#.NET

Functions
• A function is a group of related instructions that performs a specific task.
• It may or may not return a value. The function which does not return a value has a void return type.
• Be it small or big, the function will perform that task completely.
• Functions take some input as parameters and return the result as a return value.
• A function can be reused any number of times in the program hence allows us to reuse the code.
• Type of functions
• Predefined Functions (Built-In-Functions) Comes preloaded with the framework.
• User-Defined Function Created by developers at the time of development.

18
C#.NET

Functions
• Function Name: It is mandatory, and it defines the name of the method or function.
• Parameter List: It is optional, and it defines the list of parameters.
• Return Type: It is mandatory, and it defines the return type value of the method. A function may or may
not return a value, but it can return at most one value. It cannot return multiple values, but it can take
multiple values as parameters. If the function is not returning any value, then the return type should be
void.
• Access Specifier: It is optional, and it defines the scope of the method. That means it defines the
accessibility of the method such as public, protected, private etc. Default is private.
• Modifier: It is optional and defines the type of access to the method. For example, static, virtual, partial,
sealed, etc.
• Function Body: The body of the function defines our code that needs to be executed on the function call.
It is enclosed within curly braces

19
C#.NET

Return Statement
• It is a keyword.
• It terminates the execution of a
function immediately and
returns the control to the
calling function.
• It can also return a value to the
calling function.
• A return statement causes
your function to exit and
return a value to its caller.

20
C#.NET

Command Line Arguments


• Command Line Argument is a way to pass parameters to main method.
• Main(string[] args)
• The arguments which are passed by the user or programmer to the Main() method are termed as
Command-Line Arguments.

21
C#.NET

More on Strings
• We know that strings are reference type. It is an object of String Class and represents a sequence of
characters.
• Small case string is an alias to String with upper case S. Both are pointing to the same String Class.
• It a convention to use string for variable declaration and String for invoking methods.
• String are immutable.
• Mutable means can be changed. Immutable cannot be changed.
• string my_channel_name = “SatyarthProgrammingHub” //Create an object and assigns the value.
• my_channel_name = “NewSatyarthProgrammingHub” // Create another fresh object and assigns the value.
• The other value is now unreferenced in the memory and will be disposed by garbage collector.
• You can use verbatim literal or raw string literals to write a multiline string.
• String scape sequence and string interpolation.
• Substrings
• Accessing individual characters
• Null strings and empty strings
• Using stringBuilder for fast string creation

22
C#.NET

Arrays in C#
• An array is defined as a collection of similar types of values that are stored in a contiguous memory
location under a single name.
• We know a primitive type variable (int, double, bool) can hold only a single value.
• Sometimes per your business requirement, if you want to store 100 integer values, then you need to
create 100 integer variables in your program which is not a good programming approach.
• We can overcome this problem by using the concept called Arrays.
• Arrays are not new in C#, they are existing in other programming languages such as C, C++, Java, etc.
• Array uses a zero-based indexing mechanism.
• C# Supports two types of arrays
• Single Dimensional Arrays – Data is arranged in the form of a row.
• Multidimensional Arrays – Data is arranged in the form of rows and columns.
• Jagged Arrays – rows and columns are not equal
• Rectangular Arrays – rows and columns are equal

23
C#.NET

Arrays in C#
General Syntax: <data type>[] VariableName = new <data type>[size of the array];
Example: int[] Emp = new int[10];

int total_emp = 5;
int[] E = new int[total_emp];

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

var Emp = new[] {1, 2, 3 , 4, 5}; - Implicitly Typed Arrays.

Assigning and Accessing values in Arrays.


For and Foreach loops with Arrays.
24
EXCEPTION HANDLING IN
C#

C#.NET 25
C#.NET

Exception Handling in C#
• An Exception is a Class in C# which is responsible for abnormal termination of the program on
runtime errors the program execution.
• Exception Handling is a procedure to handle the exception which occurred during the execution of a
program.
• Runtime are not good at all because whenever the runtime errors occur the program gets terminated
abnormally without executing the next line of code.
• Runtime error can be frustrating to the end user and may degrade your product. So, It is a developer's
key responsibility to handle the exception.

26
C#.NET

Who is responsible for an Exception?


• Object of that expectation class is responsible for an exception.
• These exception classes are predefined in BCL (Base Class Library).
• A sperate class is defined for each sperate exception.
• IndexOutOfRangeException
• FormatException
• NullReferenceException
• DivideByZeroException
• FileNotFoundException
• SQLException
• OverFlowException
• Exception

27
C#.NET

What happens when an


Exception is raised?
• When an exception is raised the program terminate
abnormally and code placed after the statement which
got exception will not be reached/executed by CLR.
• CLR creates and exception class object based on the kind
of the exception and terminates the program by throwing
that exception object with the help of throw keyword.

28
C#.NET

Handling an Exception.
• The process of catching the exception and replacing the CLR given exception message with a custom
message and stopping the abnormal termination of the program whenever runtime errors are
occurring is called Exception Handling.
• Advantages of Exception Handling
• We can provide a custom message to end user, which will make more sense rather breaking the program.
• We can stop the abnormal termination of the application.
• Any corrective measures can be implemented that may resolve the problem.
• We can provide some high-level error correction details to the user, so that the user can try resolve the
problem, user has the appropriate privileges.

29
Ways of handling an Exception. 1. Logical Implementation
2. Try-Catch Implementation

C#.NET 30
Ways of handling an Exception. 1. Logical Implementation
2. Try-Catch Implementation

C#.NET 31
Try Catch & Finally in Exception handling.
• Try Block – Contains exception causing and its related statements. When exception occurs,
the CLR creates an instance of the Exception class based on the logical error throw it the
corresponding catch block.
• Catch Block – It is used to catch the exception thrown from its corresponding try block. It
has the logic to take necessary actions for that exception. The Catch block syntax in C# looks
like a constructor. It does not take accessibility modifiers, normal modifiers, or return types.
It takes only a single parameter of type Exception or any child class of the Exception class.
Inside the catch block, we can write code to resolve the error.
• Finally Block – Contains the code which need to be executed irrespective of an exception
has occurred or not and it means it is guaranteed that the statements that are placed in
finally block are always going to be executed no matter exception is handled by the catch
block or not.

C#.NET 32
Exception handling recap.
1. If all the statements under the try block are executed successfully then from the last
statement of the try block, the control directly jumps to the first statement that is present
after all the catch blocks without executing the catch block
2. If any of the statements in the try block causes an error, then from that statement control
will jump to Catch block without executing any other statements in the try block.
3. If a proper catch block is found that handles the exception thrown by the try block, CLR
executes the code under that catch block, and again it jumps to the first statement after all
the catch blocks.
4. If a matching catch block is not found, then the generic catch block will be executed.
5. If you don’t have the generic catch block and if any of the catch blocks are unable to handle
the exception, the program terminates abnormally.

C#.NET 33
OTHER IMPORTANT
CONCEPTS

C#.NET 34
Properties in C#
1. A property is a member of a class and used to encapsulate and protect the data members
(i.e., fields or variables) of a class.
2. It is a mechanism to get and set the values of data members of a class from outside of the
class.
3. A property in C# is never used to store any data, it just acts as a medium to transfer data.
4. Properties use special methods called as accessors.
1. Get Accessor
2. Set Accessor

C#.NET 35
Properties in C# - Accessors
1. A Get Accessor is used to get the data from the data field (variable of a class).
2. Using the get accessor, we can only get the data, we cannot set (update/modify) the data.
3. Syntax: get {return Field_Name;}

4. A Set Accessor is used to set the data (i.e., value) into a data field (a variable of a class).
5. This set accessor contains a fixed variable named value.
6. Whenever we set the data, whatever data we are supplying will be stored inside the
variable called value by default.
7. Using a set accessor, we cannot get the data.
8. Syntax: set {Field_Name = value; }

C#.NET 36
Type of Properties in C#
1. ReadOnly Property – Used to read the data from the data field (variable).
2. WriteOnly Property – Used to write data into the data field (variable).
3. ReadWrite Property – Used for both read and write data from the data field (variable).
4. Auto-Implemented Property – Don’t have additional logic to set and get data from a data
field i.e., from a variable of a class.
1. Syntax: Access_specifier Datatype PropertyName { get; set; }
2. Example: public int EmpName { get; set; }

C#.NET 37
Static Keyword in C#
1. Static modifier used to declare a static member, which belongs to the type itself rather
than to a specific object.
2. If we use static keyword with class members, then there will be a single copy of the type
member in the memory.
3. If a variable or method is declared static, we can access them using the class name. We
can use them directly(without class name) inside the same class.
4. The static modifier can be used to declare static classes.
5. If we declare a class as static, we cannot create objects of the class.
6. A static class cannot be inherited in C#.

C#.NET 38
Const and ReadOnly in C#
1. Constant and ReadOnly keyword are used to make a field constant (a value that cannot be
modified).
2. Constant (const)
1. Constant fields or local variables must be assigned a value at the time of declaration.
2. Once assigned a value cannot be modified.
3. By default, constant are static, hence you cannot/need not define a constant type as static.
4. A constant field or local variable can be initialized with a constant expression which must be fully
evaluated at compile time.
3. ReadOnly
1. A readonly field can be initialized either at the time of declaration or within the constructor of the
same class.
2. Readonly fields can be used for run-time constants.
3. We can specify a readonly field as static, since like constant, by default it is not static.

C#.NET 39
Overriding ToString() method in C#
1. ToString() method gives us the string representation of an object or type.
2. ToString() method is defined in Object Class.
3. Object Class is supper class or parent class for all the types in C#.
4. All the types in .NET Framework are inherited directly or indirectly from the Object Class.
5. Because of inheritance, every type in .NET inherits the ToString() method from the Object
Class.
6. ToString() method is defined as a Virtual Method which allows this method to be
overridden in the child classes.

C#.NET 40
ToString() and Convert. ToString() methods in C#
1. ToString() method is defined in Object Class.
2. Both methods gives us the string representation of an object or type.
3. [Link]() method handles null whereas ToString() method does not.
4. If the value of the variable, you are trying to invoke ToString method, is null then you will
get a Null Reference Exception. If you use [Link]() method, you will not get the
exception.

C#.NET 41
Boxing and Unboxing in C#
1. Checked – Boxing is the process of
converting a value type to the type
object or to any interface type
implemented by this value type. When
the common language runtime (CLR)
boxes a value type, it wraps the value
inside a [Link] instance and
stores it on the managed heap. Boxing is
implicit.
2. Unboxing – Extracts the value type from
the object. Unboxing is explicit.

C#.NET 42
Checked and Unchecked Keyword in C#
1. Checked – It is used to explicitly enable the overflow checking integral type arithmetic
operations.
2. Unchecked – It is used to suppress the overflow checking integral type arithmetic
operations.

C#.NET 43
44

THANK YOU

You might also like