[go: up one dir, main page]

0% found this document useful (0 votes)
10 views7 pages

Flow Control in Csharp

The document provides an overview of flow control in C#, including conditional statements (if, switch) and loops (for, while, do-while, foreach). It explains method parameters such as const, readonly, ref, out, and named parameters, along with static and non-static methods, access modifiers, and special methods. Additionally, it includes interview questions related to these concepts, highlighting differences between ref and out, and the use of readonly with static variables.

Uploaded by

rupams2024
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)
10 views7 pages

Flow Control in Csharp

The document provides an overview of flow control in C#, including conditional statements (if, switch) and loops (for, while, do-while, foreach). It explains method parameters such as const, readonly, ref, out, and named parameters, along with static and non-static methods, access modifiers, and special methods. Additionally, it includes interview questions related to these concepts, highlighting differences between ref and out, and the use of readonly with static variables.

Uploaded by

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

Flow Control in C#: Flow control structures determine the direction a

program takes based on conditions and iterations.


Conditional Statements:
if, else if, else

int age = 20;


if (age < 18)
{
Console.WriteLine("Minor");
}
else if (age >= 18 && age < 60)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Senior Citizen");
}

Example:
Used in online forms to validate user age and display messages accordingly.
===================
switch statement

string day = "Monday";


switch (day)
{
case "Monday":
Console.WriteLine("Workday");
break;
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Example:
Restaurant apps to show daily specials.
=======================
2. Loops in C#
Loops are used to execute a block of code repeatedly.

for (int i = 1; i <= 5; i++)


{
Console.WriteLine("Counter: " + i);
}
==============
while loop

int i = 1;
while (i <= 5)
{
Console.WriteLine("Counter: " + i);
i++;
}
==============
do-while loop

int j = 1;
do
{
Console.WriteLine("Counter: " + j);

1
j++;
} while (j <= 5);
==============
foreach loop

string[] fruits = { "Apple", "Banana", "Cherry" };


foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

Example:
Shopping cart systems to loop through selected items.

==============

Method Parameters: const, readonly, ref, out , named parameters

1. const in C#
A compile time constant
A constant value must be assigned at declaration and cannot be changed later.

It's implicitly static and belongs to the type, not instance.

Syntax: const double PI = 3.14159;

Invalid:
PI = 3.14; // Error - cannot modify const

Example:
Used in tax calculation or conversion rates that never change:
const double GST_RATE = 0.18;
2. readonly in C#
A runtime constant.
Value can be assigned: At declaration Or in the constructor
Used for values that can vary per instance but not after construction.

Syntax:
readonly int userId;

public User(int id)


{
userId = id;
}

Example:
Used for immutable configuration per object, e.g., ID assigned at account creation.
3. ref keyword: Passes argument by reference so the called method can modify the
caller's variable.
The variable must be initialized before passing.

Example:

void DoubleValue(ref int number)


{
number *= 2;
}

int x = 5;
DoubleValue(ref x);
Console.WriteLine(x); // Output: 10

Use:
Used when you want the method to modify the input value.
4. out keyword
Similar to ref, but you don’t have to initialize the variable before passing.

2
The method must assign a value before returning.

Example:

void GetDetails(out string name, out int age)


{
name = "Rupa";
age = 30;
}

string n;
int a;
GetDetails(out n, out a);
Console.WriteLine($"{n}, {a}");//error

Use:
Common in TryParse-style methods:
int number;
bool success = int.TryParse("123", out number);
5. Named Parameters
Allows calling a method with parameter names explicitly.
Makes code more readable and helps skip optional parameters.

Syntax:
void Register(string name, int age, string city = "Unknown")
{
Console.WriteLine($"{name}, {age}, {city}");
}

Register(age: 25, name: "Rupa"); // Named parameters


Use:
Useful in methods with many optional parameters or default values.
Params params-Keyword
Allows passing a variable number of arguments.

void PrintNumbers(params int[] numbers) {


foreach (var num in numbers)
Console.WriteLine(num);
}

Quick Comparison Table

Passed Must Initialize Can Modify in


Keyword Use Case
by Before Method
const N/A Yes No Compile-time constants
No (but must be set in Immutable per-instance
readonly N/A No after init
ctor) fields
Referenc
ref Yes Yes Update caller’s variable
e
Referenc
out No Yes (mandatory) Return multiple values
e
Named
N/A N/A N/A Clear method calls
Params

Static:

Definition:

3
Belongs to the type (class), not an instance.

Shared across all instances.

Can't access instance members.

Syntax:
public static int Counter = 0;
public static void ShowMessage()
{
Console.WriteLine("This is a static method.");
}

4. Non-static (Instance)

Definition:

Belongs to each object (instance).

Each object has its own copy of fields/methods.

Syntax:

public int Id;


public void DisplayId()
{
Console.WriteLine($"Id: {Id}");
}

1. Based on Declaration

Type Description
Instance
Belongs to an object instance.
Method
Static Method Belongs to the class, not an instance.
Constructor Special method called when an object is created.
Destructor Cleans up before the object is destroyed (rarely used).
Used in partial classes; declared in one part, implemented
Partial Method
optionally.
Extension
Adds methods to existing types without modifying the type.
Method

2. Based on Return Type and Parameters

Type Example Description


Void Method void SayHello() Returns nothing.
Return Method int GetSum() Returns a value.
Parameterized void Greet(string
Takes arguments.
Method name)
Method Add(int a), Add(int a, Multiple methods with same name, different
Overloading int b) parameters.

3. Access Modifiers (Visibility)

4
Modifier Description
public Accessible from anywhere.
private Accessible only within the class.
protected Accessible in the class and derived classes.
internal Accessible within the same assembly.
protected
Accessible in the same assembly and derived classes.
internal
private Accessible within the class and derived classes in the
protected same assembly.

4. Special Methods

Type Description
No implementation; must be overridden in
Abstract Method
derived class.
Virtual Method Can be overridden in derived classes.
Override Method Overrides a base class method.
Returns a Task or Task<T> for asynchronous
Async Method
operations.
Lambda/
Methods without names (inline or delegated).
Anonymous

Example

public class Calculator


{
public int Add(int a, int b) // Regular method
{
return a + b;
}

public static void ShowAppName() // Static method


{
Console.WriteLine("Simple Calculator");
}

public void PrintMessage(string msg = "Hello") // Optional parameter


{
Console.WriteLine(msg);
}
}

Quick Summary Chart

Category Types
Scope Instance, Static
Return Void, Return Type, Async
Paramete Optional, Named, ref, out,
rs params
Abstract, Virtual, Override,
Special
Extension
Others Constructor, Destructor, Partial

Basic Interview Questions

 Can readonly fields be static?

Yes, use static readonly.

5
 Difference between ref and out?

ref needs to be initialized before passing; out does not.

 Can you assign a value to a const inside constructor?

No, const must be assigned at declaration.

 Why use named parameters?

For readability and to avoid issues with parameter order.

Interview Questions

1. What happens if you try to pass an uninitialized variable using ref and out?
Explain with code.

Answer:ref requires initialization before passing.out doesn’t require initialization, but the
called method must assign a value.

Code:

void TestRef(ref int x) { x = 10; }

void TestOut(out int y) { y = 20; }

int a; // Error: use of unassigned local variable


TestRef(ref a); // Compilation Error
int b;
TestOut(out b); // Works fine

2. Can readonly be used with static variables? How does it differ from const
static?

Answer:

Yes, readonly can be combined with static.

const is compile-time constant.

readonly static is initialized at runtime (e.g., from a config file).

Example:

public static readonly string AppVersion = GetVersionFromConfig();


public const string Author = "Rupa"; // must be known at compile time

3. How can named parameters help improve code readability and maintainability?
Give an example where it prevents a bug.

Answer:
Named parameters help when methods have multiple optional or similar-typed
parameters, reducing errors from wrong order.

Example:

6
void SendEmail(string to, string subject, string body, bool isHtml = false) { }

SendEmail("a@x.com", "Hello", "<h1>Hi</h1>", true); // unclear meaning of true


SendEmail(to: "a@x.com", subject: "Hello", body: "<h1>Hi</h1>", isHtml: true); // clear

4. What’s the difference between method overloading and using optional +


named parameters? Which one should you prefer and why?

Answer: Overloading: Multiple methods with same name but different signatures.
Optional parameters: Single method with default values.

Example:

void Print(string msg) { }void Print(string msg, int count) { } // Overloaded


void Print(string msg, int count = 1) { } // Optional

Prefer optional + named for simplicity unless behavior drastically differs.

5. What happens if you modify a readonly field inside a method that is not a
constructor? Explain.

Answer:You’ll get a compile-time error. readonly can only be assigned at declaration or


in the constructor.

Example:

readonly int userId;

public void SetId()


{
// userId = 5; Error: readonly field cannot be assigned outside constructor
}

You might also like