The C# Language Basics
UNIT 2 | 12 Hrs
Yuba Raj Devkota (NCCS)
Add Two Numbers
C# Data Types
C# Type Casting
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Explicit casting must be done manually by placing the type in parentheses in front of the value:
Explicit Casting
Type Conversion
Methods
C# User Input
User Input and Numbers
C# Operators
Assignment Operators
using System; using System;
using System;
namespace MyApplication namespace MyApplication
namespace MyApplication
{ {
{
class Program class Program
class Program
{ {
{
static void Main(string[] args) static void Main(string[] args)
static void Main(string[] args)
{ {
{
int x = 5; int x = 5;
int x = 5;
x >>= 3; x <<= 3;
x |= 3;
[Link](x); [Link](x);
[Link](x);
} }
}
} }
}
} }
}
7 0 40
Comparison Operators
Logical Operators
C# Math
Returns 10 if value is less than 9.5 else 9
C# Strings
String Interpolation
Another option of string concatenation, is string interpolation, which substitutes values
of variables into placeholders in a string. Note that you do not have to worry about spaces,
like with concatenation:
Lab Exercises
Write a C# Program to
1. Print your name and address
2. Print an Integer Entered by User
3. Multiply two Floating Point Numbers Entered by User
4. Calculate the Simple Interest
5. Calculate Area and Perimeter of Circle
6. Count Number of Words in a String
Simple Interest in C#
int P, T;
Note:
float R, SI;
[Link]("Enter Amount :");
• Convert.ToInt32 is to convert a
P = Convert.ToInt32([Link]());
value to a 32-bit signed integer
[Link]("Enter Rate :");
• [Link] converts to
R = [Link]([Link]());
Single Precision (Float), which is
[Link]("Enter Time :");
32 bits.
T = Convert.ToInt32([Link]());
• [Link] converts to
SI = P * R * T / 100;
Double Precision (Double), which
[Link]("Interest is :{0}", SI);
is 64 bits
[Link]();
These Methods are part of System
[Link]();
namespace
Area and Perimeter in C#
class Program
{
static void Main(string[] args)
{
double r,perimeter, area;
[Link]("Please write the radius of your circle
: ");
r = [Link]([Link]());
perimeter = 2 * 3.14 * r;
area = 3.14 * [Link](r, 2); //area = 3.14 * r * r;
[Link]("==========================
===================");
[Link]("The perimeter of your circle :
{0}",perimeter);
[Link]("The area of your circle : {0}",
area);
[Link]();
}
}
C# Program to Count Number of Words in a String
static void Main(string[] args)
{
string sentence;
[Link]("Enter String : ");
sentence = [Link]();
string[] words = [Link](' ');
[Link]("Count of words :"+[Link]);
[Link]();
}
C# Conditions and If Statements
C# Switch
// Outputs "Looking forward to the Weekend."
C# While Loop
C# For Loop
C# Arrays
Sorting Array
Namespaces in C#
• Namespaces are used in C# to organize and provide a level of separation of codes. They
can be considered as a container which consists of other namespaces, classes, etc.
• Namespaces are not mandatory in a C# program, but they do play an important role in
writing cleaner codes and managing larger projects.
• Let's understand the concept of namespace with a real life scenario. We have a large
number of files and folders in our computer. Imagine how difficult it would be to manage
them if they are placed in a single directory. This is why we put related files and folders in
a separate directory. This helps us to manage our data properly.
• The concept of namespace is similar in C#. It helps us to organize different members by
putting related members in the same namespace.
• Namespace also solves the problem of naming conflict. Two or more classes when put
into different namespaces can have same name.
Lab Exercises
Write a C# Program to
8. Print all prime numbers in an interval (i.e. from 5 to 20)
9. Find greatest number among 3 numbers using conditional operator
10. To calculate library fine. The fee structure is as follows:
• If the book is returned on before 5 days, no fine will be charged.
• If the book is returned after the expected return day (between 5 and 10 days) – fine: 0.5$ per day
• If the book is returned after the expected return day (between 10 and 30 days) fine: 1$ per day
• If the book is not returned after 30 days, cancel membership. fine: 1.5$ per day
11. Find min and max number in an array
12. Find the factorial of a number
13. Find the longest word in an string array
Greatest of 3
numbers
1
2 class Program
3 {
4
5 static void Main(string[] args)
6 {
7 string[] arr = { "Chsarp", "Console","Examples","[Link]-console-
8 [Link]" };
9 string longWord = "";
10 int Wordcount = 0;
11 foreach (string item in arr) Finding the Longest Word in String
12 { Array using foreach loop
13 if ([Link] > Wordcount)
14 {
15 Wordcount = [Link];
16 longWord = item;
17 }
18 }
19
20 [Link]("The longest word: {0} \nLetters count : {1}", longWord,
21 Wordcount);
22 [Link]();
23 }
}
Call by Value and Call by Reference in C#
1. Call By Value in C#:
• In Call by Value, the copy of the original variable is passed to the called function.
• In Call by Value, the value of the original parameter is copied into the parameter of the function. As a
result, if we make any modifications to formal parameters, they don’t have any impact on the actual
parameter.
• It will not allow you to change the actual variables using function calls.
• The memory location referred to by formal parameters and actual arguments is different.
• It doesn’t require a ref or out keyword in C#.
2. Call By Reference in C#:
• In Call by Reference, the variable’s reference (or the actual address) is passed to the called function.
• In Call by Reference, the formal and actual parameters point to the same memory address. As a
result, any changes made to the formal parameters are also reflected in the actual parameters.
• It allows you to change the actual variable’s value using function calls.
• The memory location referred to by formal parameters and actual arguments are the same.
• It requires a ref or out keyword to achieve Call By Reference in C#.
Call by Value in C#
So, what will be printed on the Console?
If your answer is 15, then you are absolutely right because int is a value data type, and by default, it is passed by value, which
means for the above code, the variable “a” has stored the value 15 in it. When we create the variable b and assign it a, the value of
a is copied to b, and after that, if we change b, it will not affect a. This is because we have copied the value of a to b.
So, what will be printed on Console now?
It will print 15 in the console. Value is copied, so
when the UpdateValue method is called, variable
a value is copied to variable b, so changing
variable b does not change variable a.
Call by Reference in C#
we call the UpdateValue method, but we have to use the ref
keyword before the argument name. This is Call by
Reference in C# with Value Type. If you do not use the ref
keyword, you will get a compile-time error.
When you run the above code, it will print 30 on the console.
C# Program to initialize and display jagged array element with sum of each row.
// Displaying the elements and sum of each row
[Link]("Jagged Array Elements and Row
using System; Sums:");
class JaggedArrayExample for (int i = 0; i < [Link]; i++)
{ {
static void Main() [Link]("Row " + i + ": ");
{ int rowSum = 0;
// Initializing a jagged array
int[][] jaggedArray = new int[][] for (int j = 0; j < jaggedArray[i].Length; j++)
{ {
new int[] { 1, 2, 3 }, [Link](jaggedArray[i][j] + " ");
new int[] { 4, 5, 6, 7 }, rowSum += jaggedArray[i][j];
new int[] { 8, 9 } }
};
[Link](" (Sum = " + rowSum + ")");
}
[Link](); // Pause to see the output
}
}
C# Windows Forms Applications (GUI)
• Windows Forms is a Graphical User Interface(GUI) class library which is bundled
in .Net Framework.
• Its main purpose is to provide an easier interface to develop the applications for
desktop, tablet, PCs. It is also termed as the WinForms.
• The applications which are developed by using Windows Forms or WinForms are
known as the Windows Forms Applications that runs on the desktop computer.
• WinForms can be used only to develop the Windows Forms Applications not web
applications.
• WinForms applications can contain the different type of controls like labels, list
boxes, tooltip etc.
Lab Exercises
14. Create a GUI login form and validate
it with username as your first name
and password as your surname. It
should also have Clear Fields Option.
15. Design a GUI based Calculator which
can perform basic arithmetic
operations. Also create a Clear button
to clear the answer.