C#-Ist Chapter
C#-Ist Chapter
Note that the statement object myObject = new object(); combines all four of these.
In C#, the simplest method to get input from the user is by using the
ReadLine() method of the Console class. However, Read() and
ReadKey() are also available for getting input from the user. They are
also included in Console class.
C# Input
In C#, the simplest method to get input from the user is by using
the ReadLine() method of the Console class.
However, Read() and ReadKey() are also available for getting input from the
user. They are also included in Console class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
Console.ReadLine();
}
}
}
Output
1
Enter a string - Hello World
You entered 'Hello World'
C# Output
In order to output something in C#, we can use
System.Console.WriteLine() OR
System.Console.Write()
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("C# is cool");
}
}
2
}
C# is cool
int x = 4 + 3 * 5;
3
Operator Precedence Table
The higher the precedence of operator is, the higher it appears in the table
C# Operator Precedence
Category Operators
Multiplicative *, /, %
Additive +, -
Equality ==, !=
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Ternary ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
4
The assignment operators have the lowest precedence while the postfix
increment and decrement operators have the highest precedence.
namespace Operator
{
class OperatorPrecedence
{
public static void Main(string[] args)
{
int result1;
int a = 5, b = 6, c = 4;
result1 = --a * b - ++c;
Console.WriteLine(result1);
}
}
}
19
5
Operator precedence is a set of rules which defines how an expression is
evaluated. In C#, each C# operator has an assigned priority and based on
these priorities, the expression is evaluated.
For example, the precedence of multiplication (*) operator is higher than the
precedence of addition (+) operator. Therefore, operation involving
multiplication is carried out before addition.
C# Type Casting
Type casting is when you assign a value of one data type to another type.
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a
larger size type:
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in
front of the value:
6
Example
double myDouble = 9.78;
Console.WriteLine(myInt); // Outputs 9
Try it Yourself »
C# statements- Branching
Methods are executed from top to bottom. The compiler reads each
line of code in turn and executes one line after another. This continues
in sequence until the method branches. Branching means that the
current method is interrupted temporarily and a new method or
routine is executed; when that new method or routine finishes, the
original method picks up where it left off. A method can branch in
either of two ways: unconditionally or conditionally.
A branch is a contained copy of the codebase. Any code written in a branch will not interfere
with the original codebase. Many programmers use branches to fix bugs or add features to a
codebase.
void MyMethod()
{
int a; // declare an integer
a = 5; // assign it a value
console.WriteLine("a: {0}", a); // display the value
}
Beginner
Free Course
1. Break Statement in C#
The break statement is a powerful tool in the C# programming language that
allows developers to control the flow of their code. It is primarily used to exit a
loop or switch statement prematurely, based on a certain condition.
Understanding how to effectively use the break statement in c# can greatly
enhance your programming skills and make your code more efficient.
Example
Let's elaborate on this in C# Compiler.
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
Run Code >>
Explanation
This code uses a for loop to iterate over the values from 0 to 9. Inside the loop,
there is an if statement that checks if the current value of i is equal to 5. If it is,
the break statement is executed, which immediately terminates the loop.
Therefore, the loop will iterate and print the values 0, 1, 2, 3, and 4. Once i
becomes 5, the break statement is triggered, and the loop ends without printing
any further values.
Output
0
1
2
3
4
class Program
{
static void Main()
{
int i = 0;
while (i < 10)
{
if (i == 7)
{
9
break;
}
Console.WriteLine(i);
i++;
}
}
}
Run Code >>
Explanation
This code uses a while loop to iterate as long as the variable i is less than 10.
Inside the loop, there is an if statement that checks if the current value of i is
equal to 7. If it is, the break statement is executed, causing the loop to terminate
immediately. The loop starts with i initialized as 0. It then prints the value of i,
increments i by 1, and repeats the process as long as i remains less than 10 and
not equal to 7. Therefore, the loop will iterate and print the values 0, 1, 2, 3, 4, 5,
and 6. Once i becomes 7, the break statement is triggered, and the loop ends
without printing 7 or any further values
Output
0
1
2
3
4
5
6
2. Continue Statement in C#
In addition to the break statement, C# also provides the continue statement,
which allows developers to skip the remaining code within a loop iteration and
move on to the next iteration. The continue statement in C# is particularly useful
when you want to skip certain iterations based on a specific condition.
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
10
{
continue;
}
Console.WriteLine(i);
}
}
}
Run Code >>
Explanation
This code in the C# Editor prints the odd numbers from 0 to 9 (inclusive) by
skipping the even numbers using the continue statement in a loop.
Output
1
3
5
7
9
class Program
{
static void Main()
{
int i = 0;
Explanation
This code initializes i to 0 and then enters a while loop. In each iteration, i is
incremented by 1. If i is divisible by 3, the loop skips to the next iteration using
continue. Otherwise, it prints the value of i. The loop continues until it reaches 10.
Output
1
2
4
11
5
7
8
10
3. Goto Statement in C#
The goto statement in C# allows developers to transfer the control of the program
to a labeled statement within the same method, or to a labeled statement within a
different method in the same class. While the goto statement can be a powerful
tool, it should be used with caution as it can make the code harder to understand
and maintain.
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (i == 5 && j == 5)
{
goto end;
}
Console.WriteLine(i + ", " + j);
}
}
end:
Console.WriteLine("Loop exited");
}
}
Run Code >>
Explanation
This code consists of nested for loops. It iterates through the values of i and j
from 0 to 9. When i and j both equal 5, the code executes a goto statement,
jumping to the end label and exiting both loops. If the condition is not met, it
prints the values of i and j using Console.WriteLine(i + ", " + j);. After the loops or
upon goto execution, "Loop exited" is printed to the console.
12
Output
0, 0
0, 1
0, 2
0, 3
0, 4
0, 5
0, 6
0, 7
0, 8
0, 9
1, 0
1, 1
1, 2
1, 3
1, 4
1, 5
1, 6
1, 7
1, 8
1, 9
2, 0
2, 1
2, 2
2, 3
2, 4
2, 5
2, 6
2, 7
2, 8
2, 9
3, 0
3, 1
3, 2
3, 3
3, 4
3, 5
3, 6
3, 7
3, 8
3, 9
4, 0
4, 1
4, 2
4, 3
4, 4
4, 5
4, 6
4, 7
4, 8
4, 9
5, 0
5, 1
5, 2
5, 3
5, 4
Loop exited
13
2. Error handling
using System;
class Program
{
static void Main()
{
try
{
// Some code that might throw an exception
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
goto error;
}
Console.WriteLine("Code executed successfully");
error:
Console.WriteLine("Error handling code executed");
}
}
Run Code >>
Explanation
This code in the C# Online Compiler demonstrates exception handling using a
try-catch block. The try block contains the code that might throw an exception. If
an exception occurs, the catch block is executed. It prints an error message with
the exception message. Then, using the goto statement, it jumps to the error
label. Regardless of whether an exception occurred or not, the code after the
catch block is executed, printing "Code executed successfully". Finally, the code
reaches the error label and executes the error handling code, printing "Error
handling code executed".
Output
Case 1: Exception is thrown
An error occurred:
Error handling code executed
class Program
{
static void Main()
{
int i = 0;
start:
14
if (i < 10)
{
Console.WriteLine(i);
i++;
goto start;
}
}
}
Run Code >>
Explanation
This code demonstrates a loop using the goto statement. It initializes i to 0 and
labels it as start. It then enters a conditional block that checks if i is less than 10.
If true, it prints the value of i, increments it by 1, and jumps back to the start label
using goto. This process repeats until i is no longer less than 10. Essentially, it
prints the numbers from 0 to 9 and utilizes the goto statement for looping
behavior.
Output
0
1
2
3
4
5
6
7
8
9
4. Return statement in C#
In C#, the "return" statement is used within a method to explicitly specify the
value that the method should return to the caller. It can return a value of a
specified data type, or it can be used without a value in methods with a return
type of "void." Once a "return" statement is executed, it immediately exits the
method, and control is returned to the caller with the specified value, if any.
Returning an Integer
using System;
Explanation
This C# code in the C# Editor defines a method named Add that takes two
integer parameters, a and b, calculates their sum, and returns the result. When
called with values 5 and 3, it assigns the sum (8) to the variable sum and prints
"Sum is: 8" to the console.
Output
Sum is: 8
Returning a String
using System;
Explanation
This C# code defines a method called Greet that takes a string parameter name,
constructs a greeting message by appending the name to "Hello," and returns
the resulting string. When the method is called with the argument "Scholars," it
prints "Hello, Scholars!" to the console using Console.WriteLine.
Output
Hello, Scholars!
5. Throw statement in C#
16
By using the new keyword manually, this is utilized to construct an object of any
legitimate exception class. Every legitimate exception must derive from the
Exception class.
Example
using System;
public class Program
{
public static string Greet(string name)
{
string greeting = "Hello, " + name + "!";
return greeting;
}
Explanation
This C# program in the C# Playground demonstrates the use of the throw
keyword. It defines a class Scholars with a method displaysubject that throws a
NullReferenceException if the input string is null. In the Main method, it calls
displaysubject with a null argument and catches the exception, printing the
exception message if an exception occurs.
Output
Exception Message
17
enum Day {Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday};
By default enum values start at 0 and each successive
member is increased by a value of 1. As a result, the previous
enum ‘Day’ would contain the values:
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday =3
etc…
Structure (struct)
A struct is another user-defined type in C#, which holds a set
of variables. It is a lightweight class and has a limited
functionalities than a class. Some of the limitations are:
18
How to declare a struct?
To declare a struct, use the key word “struct” followed by the
name of the struct, and inside the curly braises, declare the
variables as you can see below:
you can store multiple variables of the same type in an array data structure.
You declare an array by specifying the type of its elements. If you want the
array to store elements of any type, you can specify object as its type. In the
unified type system of C#, all types, predefined and user-defined, reference
types and value types, inherit directly or indirectly from Object.
C#Copy
type[] arrayName;
C#Copy
// Declare a single-dimensional array of 5 integers.
int[] array1 = new int[5];
// Declare and set array element values.
int[] array2 = [1, 2, 3, 4, 5, 6];
// Declare a two dimensional array.
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values.
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a jagged array.
int[][] jaggedArray = new int[6][];
// Set the values of the first array in the jagged array structure.
jaggedArray[0] = [1, 2, 3, 4];
Single-dimensional arrays
A single-dimensional array is a sequence of like elements. You access
an element via its index. The index is its ordinal position in the
sequence. The first element in the array is at index 0. You create a
single-dimensional array using the new operator specifying the array
element type and the number of elements. The following example
declares and initializes single-dimensional arrays:
C#Copy
int[] array = new int[5];
string[] weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
Console.WriteLine(weekDays[0]);
Console.WriteLine(weekDays[1]);
Console.WriteLine(weekDays[2]);
Console.WriteLine(weekDays[3]);
Console.WriteLine(weekDays[4]);
Console.WriteLine(weekDays[5]);
Console.WriteLine(weekDays[6]);
/*Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/
Example:
using System;
// Using constructor
var bookTuple = new Tuple<string, string>("The Great Gatsby", "F.
Scott Fitzgerald");
21
}
}
unit 2
What is a Class in C#?
In C#, a class is a blueprint for creating objects and defining their properties,
methods, and events. It acts as a template, encapsulating data and behavior.
Classes enable object-oriented programming, promoting code reusability and
organization by grouping related functionality. Instances of classes are used to
create objects in C# programs.
A class declaration typically starts with the term class and is followed by the
identifier (name) of the class. But depending on the needs of the application,
some optional attributes can be used with class declaration.
Modifiers: A class may be internal, public, etc. The class's default modifier
is internal.
Keyword class: The type class is declared using the class keyword.
Class Identifier: There is a class variable available. The first letter of the
identifier, also known as the class name, should always be capitalized.
Base class or Super class: the name of the class's parent (superclass), if
one exists, followed by a colon. This is an optional step.
Interfaces: a list of the interfaces that the class has implemented,
separated by commas and beginning with a colon (if any). Multiple
interfaces may be implemented by a class. You can omit this.
Body: There are curly braces all around the class body.
New objects are initialized in class constructors. While methods are used to
implement the behavior of the class and its objects, fields are variables that give
the state of the class and its objects.
Class classname;
Declaring Objects
A class is said to be instantiated when an instance of the class is created. The
characteristics and actions of the class are shared by all instances. However,
each object has a different value for these characteristics, which is the state. Any
number of instances can be found within a class.
Objects refers to things present in the real world. For example, a shapes program
may have objects such as “triangle”, “square”, “circle”. An online learning system
might have objects such as “student”, and “course”.
As we declare variables, we use the syntax (type name;). This tells the compiler
that the name will be used to refer to data with the type type. This declaration
additionally sets aside the necessary amount of memory for the variable when it
is a primitive one. Consequently, a reference variable's type must strictly be a
concrete class name.
Person Employee;
using System;
namespace ConsoleApplication3
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[]args)
{
// Initializing an object of the Person class
Person person = new Person();
}
Output
Name: Employee
Age: 25
Modifier Description
23
public The code is accessible for all classes
protected The code is accessible within the same class, or in a class that is inherited from that class.
You will learn more about inheritance in a later chapter
internal The code is only accessible within its own assembly, but not from another assembly. You
will learn more about this in a later chapter
Private Modifier
If you declare a field with a private access modifier, it can only be accessed
within the same class:
class Car
{
private string model = "Rahul";
Output
Rahul
Example
class Car
{
private string model = "Mustang";
}
24
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
Public Modifier
If you declare a field with a public access modifier, it is accessible for all classes:
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
25
already are familiar with, such as Main(), but you can also create your
own methods to perform certain actions:
Create a method inside the Program class:
class Program
{
static void MyMethod()
{
// code to be executed
}
}
Example Explained
MyMethod() is the name of the method
static means that the method belongs to the Program class and not an
object of the Program class. You will learn more about objects and how
to access methods through objects later in this tutorial.
void means that this method does not have a return value. You will
learn more about return values later in this chapter
Example:
using System;
namespace ConsoleApplication4
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
}
Output
I just got executed!
26
}
C# Method Parameters
❮ PreviousNext ❯
Information can be passed to methods as parameter. Parameters act as variables inside the method.
They are specified after the method name, inside the parentheses. You can add as many parameters as
you want, just separate them with a comma.
The following example has a method that takes a string called fname as parameter. When the method is
called, we pass along a first name, which is used inside the method to print the full name:
Example
Output
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
// Liam is 5
// Jenny is 8
// Anja is 31
Constructors
A constructor is a special method that is used to initialize objects. The advantage
of a constructor, is that it is called when an object of a class is created. It can be
used to set initial values for fields:
Note that the constructor name must match the class name, and it cannot
have a return type (like void or int).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, C# creates one for you. However, then you are not able to set initial
values for fields.
Create a constructor:
// Create a Car class
class Car
{
public string model; // Create a field
// Outputs "Mustang"
29