0% found this document useful (0 votes)
11 views29 pages

C#-Ist Chapter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

C#-Ist Chapter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

C#

What is initialization in C#?


Initialize means to give an initial value to. In some languages, if you don't initialize
a variable it will have arbitrary (dirty/garbage) data in it. In C# it is actually a
compile-time error to read from an uninitialized variable. Assigning is simply the
storing of one value to a variable.
Assigning is simply the storing of one value to a variable. x = 5 assigns the
value 5 to the variable x. In some languages, assignment cannot be combined with
declaration, but in C# it can be: int x = 5;.

Note that the statement object myObject = new object(); combines all four of these.

 new object() instantiates a new object object, returning a reference to it.


 object myObject declares a new object reference.
 = initializes the reference variable by assigning the value of the reference to
it.

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'

Difference between ReadLine(), Read() and ReadKey()


method:
The difference between ReadLine() , Read() and ReadKey() method is:
 ReadLine() : The ReadLine() method reads the next line of input from the
standard input stream. It returns the same string.
 Read() : The Read() method reads the next character from the standard input
stream. It returns the ascii value of the character.
 ReadKey() : The ReadKey() method obtains the next key pressed by user. This
method is usually used to hold the screen until user press a key.

C# Output
In order to output something in C#, we can use

System.Console.WriteLine() OR

System.Console.Write()

Here, System is a namespace, Console is a class within


namespace System and WriteLine and Write are methods of class Console .

Let's look at a simple example that prints a string to output screen.

Example 1: Printing String using WriteLine()

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("C# is cool");
}
}

2
}

When we run the program, the output will be

C# is cool

C# Operator Precedence and


Associativity
C# Operator Precedence
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.
Take a look at the statement below.

int x = 4 + 3 * 5;

What will be the value of x after executing this statement?


The operand 3 is associated with + and * . As stated earlier, multiplication has
a higher precedence than addition. So, the operation 3 * 5 is carried out
instead of 4 + 3. The value of variable x will be 19 .

If addition would have a higher precedence, 4 + 3 would be evaluated first


and the value of x would be 35 .

3
Operator Precedence Table
The higher the precedence of operator is, the higher it appears in the table

C# Operator Precedence

Category Operators

Postfix Increment and Decrement ++, --

Prefix Increment, Decrement and Unary ++, --, +, -, !, ~

Multiplicative *, /, %

Additive +, -

Shift <<, >>

Relational <, <=, >, >=

Equality ==, !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Ternary ?:

Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

4
The assignment operators have the lowest precedence while the postfix
increment and decrement operators have the highest precedence.

Example 1: Operator Precedence


using System;

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);

}
}
}

When we run the program, the output will be:

19

C# Operator Precedence and


Associativity
C# Operator Precedence

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.

In C#, there are two types of casting:

 Implicit Casting (automatically) - converting a smaller type to a larger


type size
char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size


type
double -> float -> long -> int -> char

Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a
larger size type:

ExampleGet your own C# Server


int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

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;

int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 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
}

Jump Statement in C#: Break,


Continue, Goto, Return and Throw
23 May 2024

Beginner

Free Course

Jump Statement in C#: An Overview


7
Jump Statements in C# are essential programming tools that allow developers to
control the flow of execution within a program. Understanding how "break,"
"continue," "return," “throw” and "goto" statements work is crucial for
building efficient and logically structured C# code. Let's explore these statements
and their applications in detail. In this C# Tutorial, we will explore more about
jump Statements in C# which will include Understanding how "break,"
"continue," "return," “throw” and "goto" statements work.

What are Jump Statements in C#?


Jump statements in C# alter the flow of program execution. 'break' exits loops,
'continue' skips the rest of the loop body, and 'return' exits a method, providing
flexibility and control in program logic, enabling efficient handling of various
conditions and iterations.
There are five keywords in the Jump Statements:
1. break
2. continue
3. goto
4. return
5. throw

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 };

foreach (int num in numbers)


{
if (num % 5 == 0)
{
Console.WriteLine("Found the number: " + num);
break;
}
}
}
}
Run Code >> Found the number: 5
8
Examples of using the break statement in loops
The break statement can be used with various types of loops in C#, including for,
foreach, and while loops. Here are some examples of how the break statement
can be used in different loop scenarios:

1. Using break in a for loop


using System;

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

2. Using break in a while loop


using System;

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.

Examples of using the continue statement in loops


Here are a few examples of how the continue statement can be used in different
loop scenarios:

1. Using continue in a for loop


using System;

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

2. Using continue in a while loop


using System;

class Program
{
static void Main()
{
int i = 0;

while (i < 10)


{
i++;
if (i % 3 == 0)
{
continue;
}
Console.WriteLine(i);
}
}
}
Run Code >>

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.

Examples of using the goto statement in C#


Here are a few examples of how the goto statement can be used in different
scenarios:

1. Breaking out of nested loops


using System;

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

Case 2: No exception is thrown

Code executed successfully


Error handling code executed

3. Simplifying complex control flow


using System;

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.

Examples of using the return statement in C#

Returning an Integer

using System;

public class Program


{
public int Add(int a, int b)
{
int result = a + b;
return result;
}

public static void Main()


15
{
// Creating an instance of Program
Program programInstance = new Program();

// Calling the method using the instance


int sum = programInstance.Add(5, 3);
Console.WriteLine("Sum is: " + sum);
}
}
Run Code >>

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;

public class Program


{
public string Greet(string name)
{
string greeting = "Hello, " + name + "!";
return greeting;
}

public static void Main()


{
// Calling the method
string message = Greet("Scholars");
Console.WriteLine(message);
}
}
Run Code >>

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;
}

public static void Main()


{
// Calling the method
string message = Greet("Scholars");
Console.WriteLine(message);
}
}
Run Code >>

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

An enumeration is a user-defined data type that enables a developer


to create a variable with a fix set of possible values. For instance:
since there are only seven possible days of the week, we can use an
enumeration to define the day of the week.

How to create an enumeration?


The following example shows the syntax of creation an enum
called Day, which holds the days of the week.

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…

How to access the elements contained in an enum?


Let’s see how to access Saturday for instance.
Day favoriteDay = Day.Saturday

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:

· A struct cannot declare a default constructor. This is done


by the CLR (Common Language Run-Time)

· A struct cannot inherit another struct or class, and it cannot


also be a base for another struct or class; however, it can
implement an interface.

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:

In this example, Books is the name of the struct which


contains four elements.

How to access elements in a struct?


To access the elements, we have to instantiate the struct by
using the key word “new”, as we do with classes in java, or
without the key word “new” as shown in the example bellow.
Array

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;

An array has the following properties:

 An array can be single-dimensional, multidimensional, or jagged.


 The number of dimensions are set when an array variable is declared.
The length of each dimension is established when the array instance is
created. These values can't be changed during the lifetime of the
instance.
 A jagged array is an array of arrays, and each member array has the
default value of null.
 Arrays are zero indexed: an array with n elements is indexed
from 0 to n-1.
19
 Array elements can be of any type, including an array type.
 Array types are reference types derived from the abstract base
type Array. All arrays implement IList and IEnumerable. You can use
the foreach statement to iterate through an array. Single-dimensional
arrays also implement IList<T> and IEnumerable<T>.

 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
 */

In C#, a Tuple is a versatile data structure that allows


developers to group multiple elements together, creating a
lightweight container for storing and accessing data. Tuples
20
provide a convenient way to represent and pass around sets
of related values without the need for creating custom
classes or structures. In this article, we will explore the
concept of Tuples in C#, its benefits, and demonstrate its
usage through practical examples.

1. What is a Tuple in C#?

A Tuple is an immutable data structure introduced in C# 4.0


that can hold a fixed number of elements of different data
types. It is defined by the System namespace and is ideal for
scenarios where a lightweight data container is required to
hold temporary or transient data.

1. Creating Tuples in C#:

To create a Tuple in C#, you can use various factory methods


or simply use the Tuple constructor. The Tuple class provides
overloads for creating tuples with up to eight elements
(although, for readability, it’s recommended to use tuples
with fewer elements).

Example:

using System;

public class Program


{
public static void Main(string[] args)
{
// Using factory method
var personTuple = Tuple.Create("John", 30, true);

// 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;

What is an Object in C#?


In C#, an object is a fundamental data type that represents a real-world entity. It
combines data (variables) and methods (functions) that operate on the data,
encapsulating behavior and state. Objects are instances of classes, defining their
structure and behavior, facilitating the principles of object-oriented programming
in C#.
An object consists of:
 State: It is represented by attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
22
Consider Person as an object and see the below diagram for its identity, state,
and behavior.

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();

// Setting properties of the object


person.Name = "Employee";
person.Age = 25;

// Displaying object properties


Console.WriteLine("Name: " + person.Name);
Console.WriteLine("Age: " + person.Age);
Console.ReadLine();
}

}
Output
Name: Employee
Age: 25

Modifier Description

23
public The code is accessible for all classes

private The code is only accessible within the same class

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

C# has the following access modifiers:

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";

static void Main(string[] args)


{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

Output
Rahul

If you try to access it outside the class, an error will occur:

Example

class Car
{
private string model = "Mustang";
}

24
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

The output will be:

'Car.model' is inaccessible due to its protection level


The field 'Car.model' is assigned but its value is never used

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);
}
}

The output will be:


Mustang
C# Methods
1) A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
2) Methods are used to perform certain actions, and they are also
known as functions.3)Why use methods? To reuse code: define the
code once, and use it many times.
Create a Method
A method is defined with the name of the method, followed by
parentheses (). C# provides some pre-defined methods, which you

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!");
}

static void Main(string[] args)


{
MyMethod();
Console.ReadLine();
}

}
Output
I just got executed!

Call at multipl times


static void MyMethod()
{
Console.WriteLine("I just got executed!");

26
}

static void Main(string[] args)


{
MyMethod();
MyMethod();
MyMethod();
}

// I just got executed!


// I just got executed!
// I just got executed!

C# Method Parameters
❮ PreviousNext ❯

Parameters and Arguments

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

static void MyMethod(string fname)


{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}

Output

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from


the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.
27
Multiple Parameters
You can have as many parameters as you like, just separate them with commas:
Example
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}

static void Main(string[] args)


{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}

// 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

// Create a class constructor for the Car class


public Car()
{
28
model = "Mustang"; // Set the initial value for model
}

static void Main(string[] args)


{
Car Ford = new Car(); // Create an object of the Car Class (this will call the
constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}

// Outputs "Mustang"

29

You might also like