0% found this document useful (0 votes)
4 views16 pages

MODULE 2-Part 1

Its c# .net notes bca 5th semester

Uploaded by

Akku
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)
4 views16 pages

MODULE 2-Part 1

Its c# .net notes bca 5th semester

Uploaded by

Akku
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
You are on page 1/ 16

MODULE 2 -FIRST PART -C#

1.Introducing C#

* Need of C#:(2 marks) or Features of C#

• A modern, object-oriented, type-safe programming language developed by Microsoft.

• C# developed by Anders Hylsberg.(1 mark)

• Easy to learn than C and C++

• Strong resemblance with Java

• Part of the .NET framework, enabling development for Windows, web (ASP.NET), Combines
the power of C++ with the ease of Visual Basic and Java.

Strongly typed, and features automatic memory management.

• Automatic garbage collection.

C# is derived from C and C++ (1 mark)

2. Relationship of C# and .NET

C# is designed and used with microsoft .NET framework

3. C# Pre-processor Directives:

* Instructions to the compiler to process information before actual compilation.

* Start with #. Common directives include:

* #define, #undef: Define or undefine symbols.

* #if, #elif, #else, #endif: Conditional compilation.

* #warning, #error: Generate compiler warnings or errors.

* #pragma warning: Enable or disable specific warnings.

4 Creating a Simple C# Console Application:

* Steps:

* Open Visual Studio (or a code editor like VS Code).

* Create a new project.

* Select "Console Application" template.

* Write code inside the Main method of Program.cs.

* Console.WriteLine("Hello, World!"); is a typical first line.

* Run (F5 or Ctrl+F5).

5 Basic Structure of C# program:(4 marks)


using System; // Imports the System namespace

namespace MyFirstApp // Organizes related classes

class Program // Defines a class

static void Main(string[] args) // Entry point of the application

// Your code here

Console.WriteLine("Hello, C#!");

Console.Read(); // Keeps console open until key is pressed

6. Basic elements of C#(4 marks)

a)* Identifiers and Keywords:

* Identifiers: Names given to variables, methods, classes, namespaces, etc.

Rules:-

* Must start with a letter or underscore.

* Can contain letters, digits, and underscores.

* Case-sensitive.

* Cannot be a C# keyword.

* Keywords: Predefined Reserved words in C# with special meaning (e.g., class, public, static, void,
int, if). They cannot be used as identifiers.

b)Literals are value constants.

Literals are classified into Numeric literals,Boolean literals and character literals.

Numeric literals are again divided into Integer and Real literals.

Character literals are again divided into single character,string character and Boolean character
literals.

c) Punctuators or Separators(1 mark)


Punctuators are symbols that are used for grouping and separating.

Example:- semicolon(;),colony(:),comma(,),parenthesis()

7)d)Data Types(4,15 marks) ,Variables, Constants

Answer:- 7,8,9

* Data Types: Define the type of data a variable can hold (e.g., integer, floating-point number,
character, boolean).

C# datatypes are divided into Value types,Pointer type and Reference type

1* Value Types:

* Store their own data directly in memory.

* Accessed directly.

* Examples: int, float, double, char etc.

* When assigned to another variable, a copy of the value is made.

2 * Reference Types:

* Store a reference (memory address) to the data, not the data itself.

* Data is stored on the heap.

* Examples: class, interface, string, object, array.

* When assigned to another variable, the reference is copied, pointing to the same data in
memory.

3.Pointer data type: Store the memory address of another data type. The data can be accessed using
pointers.

* Variables:

* Named storage locations for data.

* Declared with a data type and an identifier: dataType variableName;

* Can be assigned a value: int age = 30;

* Constants:

* Variables whose values cannot be changed after initialization.

* Declared using the const keyword: const double PI = 3.14159;

* Must be initialized at the time of declaration.

8)* Type Conversions: or type casting(4 marks)

* Implicit Conversion (Widening): Automatic conversion when no data loss is possible (e.g., int to
long, float to double).

* Explicit Conversion (Narrowing/Casting): Requires a cast operator and might result in data loss
(e.g., double to int).
* Syntax: (targetType)expression; (e.g., int myInt = (int)myDouble;)

9) * Boxing and Unboxing:(15 marks)

* Boxing: The process of converting a value type to the object type (or to any interface type
implemented by the value type).

* Occurs implicitly. Creates a new object on the heap and copies the value type's data into it.

* Example:

int i=123;

object obj = i; (where 123 is an int value type).

* Unboxing: The explicit process of converting the object type back to a value type.

* Requires an explicit cast. Checks if the object instance holds the correct value type.

* Example:

object obj = 245;

int i = (int)obj;

Example program

using System;

class BoxingUnboxingDemo

static void Main()

int num = 25; // Value type

object boxedNum = num; // Boxing

Console.WriteLine("Boxed value: " + boxedNum);

int unboxedNum = (int)boxedNum; // Unboxing

Console.WriteLine("Unboxed value: " + unboxedNum);

// Modify unboxed value

unboxedNum += 10;
Console.WriteLine("Modified Unboxed value: " + unboxedNum);

Console.WriteLine("Original Boxed value remains: " + boxedNum);

Output:

Boxed value: 25

Unboxed value: 25

Modified Unboxed value: 35

Original Boxed value remains: 25

10) Operators and types of operators (4,15 marks)

Operators in C# are used to perform operations on variables and values. C# provides a rich set of
operators categorized by the type of operations they perform.

1. Arithmetic Operators

Used to perform basic mathematical operations.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (Remainder) a % b

Example:

int a = 10, b = 3;

Console.WriteLine(a + b); // 13

Console.WriteLine(a % b); // 1
2. Relational (Comparison) Operators

Used to compare values.

Operator Description

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater or equal

<= Less or equal

Example:

if (a > b) {

Console.WriteLine("a is greater");

3. Logical Operators

Used to combine conditional statements.

Operator Description

&& Logical AND

! Logical NOT

Example:

if (a > 0 && b > 0) {

Console.WriteLine("Both are positive");

}
4. Assignment Operators

Used to assign values to variables.

Operator Description

= Assign

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign

Example:

int x = 5;

x += 3; // x = x + 3

5. Unary Operators

Operate on a single operand.

Operator Description

+ Unary plus

- Unary minus

++ Increment

-- Decrement

! Logical NOT

Example:
int i = 5;

Console.WriteLine(++i); // 6

6. Bitwise Operators

Used to perform bit-level operations.

Operator Description

& Bitwise AND

` `

^ Bitwise XOR

~ Bitwise NOT

<< Left shift

>> Right shift

Example:

int x = 5; // 0101

int y = 3; // 0011

Console.WriteLine(x & y); // 0001 = 1

7. Conditional / Ternary Operator

Used for shorthand if-else.

int age = 20;

string result = (age >= 18) ? "Adult" : "Minor";

8. Type Checking and Casting Operators

Operator Description
is Checks if an object is of a type

as Casts if possible, else null

typeof Gets the System.Type

sizeof Gets the size of a data type (unsafe)

Example:

object obj = "Hello";

if (obj is string) {

Console.WriteLine("It's a string");

9. Null-coalescing Operators

Operator Description

?? Returns left if not null

??= Assigns right if left is null

Example:

string name = null;

string result = name ?? "Default"; // result = "Default"

11)Explain in detail about call by value or value type parameter and call by reference or reference
type parameter comparison.

1. Call by Value (Value Type Parameter

When a value is passed by value, a copy of the variable is sent to the method. Changes made inside
the method do not affect the original variable.

Example:

using System;

class Program {
static void ChangeValue(int x) {

x = 100;

static void Main() {

int num = 10;

ChangeValue(num);

Console.WriteLine("Outside method: " + num); // Output: 10

Explanation: num remains unchanged because only a copy was modified.

2. Call by Reference (Reference Type Parameter)

When a parameter is passed by reference, the method receives the reference (memory address) of
the original variable, so changes inside the method affect the original variable.

Example:

using System;

class Program {

static void ChangeValue(ref int x) {

x = 100;

static void Main() {

int num = 10;

ChangeValue(ref num);

Console.WriteLine("Outside method: " + num); // Output: 100

12)* Operator Precedence:


Operator Precedence and Associativity

Operator Precedence:

Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first.

Associativity:

Associativity defines the direction (left to right or right to left) in which operators of the same
precedence are evaluated.

Common Operator Precedence (High to Low):

Precedence Operators Associativity

Highest (), [], ., ++, -- Left to Right

*, /, % Left to Right

+, - Left to Right

<, <=, >, >= Left to Right

==, != Left to Right

&&, `

=, +=, -= etc. Right to Left

13) * Using the ?? (Null Coalescing) Operator:

* Provides a default value for nullable types or reference types if they are null.

* Syntax: expression1 ?? expression2

* If expression1 is not null, its value is returned; otherwise, expression2's value is returned.

Null-coalescing Operators

Operator Description

?? Returns left if not null

??= Assigns right if left is null


Example:

string name = null;

string result = name ?? "Default"; // result = "Default"

14)* Using the Scope Resolution Operator:(1 mark)

* The term "Scope Resolution Operator" (::) is primarily associated with C++.

* In C#, the equivalent functionality for accessing members of a class or namespace is achieved
using the dot operator (.).

*15) Using the is and as Operators:

* is operator:

* Checks if an object is compatible with a given type.

* Returns true if the object can be cast to the specified type without throwing an exception;
otherwise, false.

* Example: if (obj is string)

* Can also be used with pattern matching for more concise checks and casting: if (obj is string s)

* as operator:

* Attempts to cast an object to a specified type.

* If the cast is successful, it returns the cast object; otherwise, it returns null.

* Does not throw an exception on failure.

* Can only be used with reference types or nullable value types.

* Example: string str = obj as string; if (str != null)

16)Difference between Convert.ToInt32()) and int.Parse() methods

Convert class (e.g., Convert.ToInt32()) and Parse() methods (e.g., int.Parse()) for string conversions.

• Convert.ToInt32() allows null value. It convert a specified string representation of a number


to an equivalent 32 bit signed integer.

• int.Parse () does not allow null value and it convert string representation to a corresponding
numerical integer value.

17) Difference-between Console.Write and Console.Writeline in-c-sharp

The only difference between the Write() and WriteLine() is that Console.Write is used to print data
without printing the new line, while Console.WriteLine is used to print data along with printing the
new line.

Program 1: Example of Console.Write() in C#.


using System;

public class GFG

static void Main(string[] args)

Console.Write("Geeks");

Console.Write("For");

Console.Write("Geeks");

Output:

GeeksForGeeks

Program 2: Example of Console.WriteLine() in C#.

using System;

public class GFG

static void Main(string[] args)

Console.WriteLine("Geeks");

Console.WriteLine("For");

Console.WriteLine("Geeks");

Output:

Geeks

For

Geeks
18)Control Flow statements in C#(4,15 mark)

* Selection Statements: Execute different blocks of code based on conditions.

* if, else if, else:

if (condition1) { /* code */ }

EXAMPLE:- EVEN OR ODD PROGRAM

else if (condition2) { /* code */ }

else { /* code */ }

EXAMPLE:- GREATEST OF THREE NUMBERS PROGRAM

* switch: Provides a way to choose among a set of discrete values.

switch (expression)

case value1: /* code */; break;

case value2: /* code */; break;

default: /* code */; break;

* Iteration Statements (Loop control stmts in c#): Execute a block of code repeatedly.

* for loop: For known number of iterations.

for (initialization; condition; increment/decrement) { /* code */ }

EXAMPLE:- FACTORIAL OF A NUMBER PROGRAM

* foreach loop: Iterates over collections (arrays, lists).

foreach (var item in collection) { /* code */ }

EXAMPLE:- FROM PDF

* while loop: Entry Controlled loop

Executes as long as a condition is true (condition checked before each iteration).

while (condition) { /* code */ }

EXAMPLE:-

int a=0;

while(a<3)

Console.Writeline(a);
a++;

Output:0 1 2

* do-while loop: Exit controlled loop

Executes at least once, then continues as long as a condition is true (condition checked after each
iteration).

do { /* code */ } while (condition);

EXAMPLE:-

int a=4;

do

Console.Writeline(a);

a++;

while(a<3);

Output: 4

* Jump Statements: Transfer control to another part of the program.

* break: Exits the innermost loop or switch statement.

* continue: Skips the rest of the current loop iteration and proceeds to the next.

* return: Exits the current method and optionally returns a value.

* goto: Transfers control directly to a labeled statement (generally discouraged for maintainability).

19)Namespaces

* Namespaces: Used to organize code and avoid name collisions.

* Logical grouping of related classes, interfaces, structs, enums, and delegates.

* Declared using the namespace keyword.

* The System namespace:

* The fundamental namespace in C# and .NET.

* using System;

Fundamental classes like console,used for input and output operations.

20)param array in c#
params Array in C#

The params keyword in C# allows you to pass a variable number of arguments to a method as a
single parameter array. It makes method calls more flexible by letting you pass any number of
arguments (including none) of the specified type.

Syntax:

returnType MethodName(params dataType[] parameterName)

Example 1: Using params

using System;

class Program {

static void PrintNumbers(params int[] numbers) {

foreach (int num in numbers) {

Console.Write(num + " ");

static void Main() {

PrintNumbers(1, 2, 3, 4); // Pass individual arguments

Console.WriteLine();

PrintNumbers(); // No arguments

Output:

1234

You might also like