0% found this document useful (0 votes)
384 views51 pages

C# Code Output Questions and Answers

The document contains a series of C# programming questions and their expected outputs, covering fundamental topics such as data types, control flow, arrays, methods, object-oriented programming, error handling, and advanced topics. Each question is accompanied by a code snippet and the corresponding output that a candidate should expect when running the code. This collection serves as a resource for assessing a candidate's understanding of C# and their problem-solving skills.

Uploaded by

snehanila25
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)
384 views51 pages

C# Code Output Questions and Answers

The document contains a series of C# programming questions and their expected outputs, covering fundamental topics such as data types, control flow, arrays, methods, object-oriented programming, error handling, and advanced topics. Each question is accompanied by a code snippet and the corresponding output that a candidate should expect when running the code. This collection serves as a resource for assessing a candidate's understanding of C# and their problem-solving skills.

Uploaded by

snehanila25
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

Question 1: Basic Data Types

csharp

Copy code

using System;

class Program

static void Main()

int a = 10;

double b = 5.5;

[Link](a + b);

Expected Output:

Copy code

15.5

Question 2: String Concatenation

csharp

Copy code

using System;

class Program

static void Main()

string name = "World";


string greeting = "Hello " + name;

[Link](greeting);

Expected Output:

Copy code

Hello World

Question 3: Conditional Statements

csharp

Copy code

using System;

class Program

static void Main()

int x = 10;

if (x > 5)

if (x < 15)

[Link]("Inside inner if");

else

[Link]("Inside outer else");

}
}

else

[Link]("Inside outer else");

Expected Output:

kotlin

Copy code

Inside inner if

Question 4: Looping

csharp

Copy code

using System;

class Program

static void Main()

for (int i = 0; i < 3; i++)

[Link](i + " ");

Expected Output:
Copy code

012

Question 5: Array Indexing

csharp

Copy code

using System;

class Program

static void Main()

int[] arr = { 1, 2, 3, 4, 5 };

[Link](arr[2]);

Expected Output:

Copy code

Question 6: Value vs Reference Types

csharp

Copy code

using System;

class Program

static void Main()

{
int x = 5;

int y = x;

y = 10;

[Link](x); // What will be the output?

Expected Output:

Copy code

Question 7: Exception Handling

csharp

Copy code

using System;

class Program

static void Main()

try

int[] numbers = { 1, 2, 3 };

[Link](numbers[5]);

catch (IndexOutOfRangeException)

[Link]("Index out of range");

}
}

Expected Output:

sql

Copy code

Index out of range

Question 8: Class and Object

csharp

Copy code

using System;

class Person

public string Name { get; set; }

public Person(string name)

Name = name;

class Program

static void Main()

Person p = new Person("Alice");

[Link]([Link]);
}

Expected Output:

Copy code

Alice

Question 9: Static vs Non-Static Methods

csharp

Copy code

using System;

class MyClass

public static void StaticMethod()

[Link]("Static Method");

public void InstanceMethod()

[Link]("Instance Method");

class Program

static void Main()

{
[Link]();

// [Link](); // Uncommenting this line will cause a


compilation error

Expected Output:

sql

Copy code

Static Method

Question 10: Overloading Methods

csharp

Copy code

using System;

class MyClass

public void Print(int number)

[Link]("Number: " + number);

public void Print(string text)

[Link]("Text: " + text);

}
class Program

static void Main()

MyClass obj = new MyClass();

[Link](5);

[Link]("Hello");

Expected Output:

makefile

Copy code

Number: 5

Text: Hello

These questions cover a range of fundamental topics in C#, from basic


syntax and control structures to object-oriented principles. They are useful
for assessing a candidate's basic understanding of the language and their
problem-solving skills.

still 50 questions

ChatGPT

Certainly! Here is a comprehensive list of 50 C# program output questions.


These cover various aspects of the language, including data types, control
flow, collections, and object-oriented programming.

Basic Data Types and Operations

1. Integer Operations

csharp

Copy code

using System;
class Program

static void Main()

int a = 8;

int b = 3;

[Link](a / b);

Expected Output:

Copy code

2. Floating Point Precision

csharp

Copy code

using System;

class Program

static void Main()

double a = 5.0 / 3.0;

[Link](a);

Expected Output:
Copy code

1.6666666666666667

3. Boolean Logic

csharp

Copy code

using System;

class Program

static void Main()

bool x = true;

bool y = false;

[Link](x && y);

Expected Output:

graphql

Copy code

False

4. String Concatenation

csharp

Copy code

using System;

class Program

{
static void Main()

string a = "Hello";

string b = "World";

[Link](a + " " + b);

Expected Output:

Copy code

Hello World

5. String Interpolation

csharp

Copy code

using System;

class Program

static void Main()

string name = "Alice";

int age = 30;

[Link]($"Name: {name}, Age: {age}");

Expected Output:

yaml

Copy code
Name: Alice, Age: 30

Control Flow

6. If-Else Statement

csharp

Copy code

using System;

class Program

static void Main()

int x = 10;

if (x > 5)

[Link]("Greater");

else

[Link]("Smaller");

Expected Output:

mathematica

Copy code

Greater

7. Nested If Statements
csharp

Copy code

using System;

class Program

static void Main()

int x = 20;

if (x > 10)

if (x < 30)

[Link]("Between 10 and 30");

Expected Output:

mathematica

Copy code

Between 10 and 30

8. Switch Statement

csharp

Copy code

using System;
class Program

static void Main()

int day = 3;

switch (day)

case 1:

[Link]("Monday");

break;

case 2:

[Link]("Tuesday");

break;

case 3:

[Link]("Wednesday");

break;

default:

[Link]("Weekend");

break;

Expected Output:

mathematica

Copy code

Wednesday

9. For Loop
csharp

Copy code

using System;

class Program

static void Main()

for (int i = 0; i < 3; i++)

[Link](i + " ");

Expected Output:

Copy code

012

10. While Loop

csharp

Copy code

using System;

class Program

static void Main()

int i = 0;
while (i < 3)

[Link](i + " ");

i++;

Expected Output:

Copy code

012

Arrays and Collections

11. Array Access

csharp

Copy code

using System;

class Program

static void Main()

int[] numbers = { 1, 2, 3, 4, 5 };

[Link](numbers[3]);

Expected Output:

Copy code

4
12. Array Iteration

csharp

Copy code

using System;

class Program

static void Main()

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (var number in numbers)

[Link](number + " ");

Expected Output:

Copy code

12345

13. Array Initialization

csharp

Copy code

using System;

class Program

static void Main()


{

int[] numbers = new int[3];

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

[Link](numbers[1]);

Expected Output:

Copy code

20

14. List Usage

csharp

Copy code

using System;

using [Link];

class Program

static void Main()

List<int> numbers = new List<int> { 1, 2, 3 };

[Link](4);

[Link]([Link]);

Expected Output:
Copy code

15. List Iteration

csharp

Copy code

using System;

using [Link];

class Program

static void Main()

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

foreach (string name in names)

[Link](name + " ");

Expected Output:

Copy code

Alice Bob Charlie

Functions and Methods

16. Simple Method

csharp

Copy code

using System;
class Program

static void PrintMessage()

[Link]("Hello World");

static void Main()

PrintMessage();

Expected Output:

Copy code

Hello World

17. Method with Parameters

csharp

Copy code

using System;

class Program

static void Greet(string name)

[Link]("Hello, " + name);

}
static void Main()

Greet("Alice");

Expected Output:

Copy code

Hello, Alice

18. Method with Return Value

csharp

Copy code

using System;

class Program

static int Add(int a, int b)

return a + b;

static void Main()

[Link](Add(5, 3));

Expected Output:
Copy code

19. Method Overloading

csharp

Copy code

using System;

class Program

static void Display(int value)

[Link]("Integer: " + value);

static void Display(string value)

[Link]("String: " + value);

static void Main()

Display(42);

Display("Hello");

Expected Output:

makefile
Copy code

Integer: 42

String: Hello

20. Recursive Method

csharp

Copy code

using System;

class Program

static int Factorial(int n)

if (n <= 1) return 1;

return n * Factorial(n - 1);

static void Main()

[Link](Factorial(5));

Expected Output:

Copy code

120

Object-Oriented Programming

21. Class Definition

csharp
Copy code

using System;

class Person

public string Name;

public void Greet()

[Link]("Hello, " + Name);

class Program

static void Main()

Person p = new Person();

[Link] = "Alice";

[Link]();

Expected Output:

Copy code

Hello, Alice

22. Constructor Usage

csharp
Copy code

using System;

class Person

public string Name;

public Person(string name)

Name = name;

public void Greet()

[Link]("Hello, " + Name);

class Program

static void Main()

Person p = new Person("Bob");

[Link]();

Expected Output:
Copy code

Hello, Bob

23. Inheritance

csharp

Copy code

using System;

class Animal

public void Eat()

[Link]("Eating");

class Dog : Animal

public void Bark()

[Link]("Barking");

class Program

static void Main()

{
Dog d = new Dog();

[Link]();

[Link]();

Expected Output:

Copy code

Eating

Barking

24. Polymorphism

csharp

Copy code

using System;

class Animal

public virtual void Speak()

[Link]("Animal sound");

class Dog : Animal

public override void Speak()

[Link]("Woof");
}

class Program

static void Main()

Animal a = new Dog();

[Link]();

Expected Output:

Copy code

Woof

25. Abstract Class

csharp

Copy code

using System;

abstract class Shape

public abstract void Draw();

class Circle : Shape

public override void Draw()


{

[Link]("Drawing a Circle");

class Program

static void Main()

Shape s = new Circle();

[Link]();

Expected Output:

css

Copy code

Drawing a Circle

Error Handling

26. Try-Catch Block

csharp

Copy code

using System;

class Program

static void Main()

{
try

int[] numbers = { 1, 2, 3 };

[Link](numbers[5]);

catch (IndexOutOfRangeException)

[Link]("Index out of range");

Expected Output:

sql

Copy code

Index out of range

27. Finally Block

csharp

Copy code

using System;

class Program

static void Main()

try

[Link]("In try block");


}

finally

[Link]("In finally block");

Expected Output:

csharp

Copy code

In try block

In finally block

28. Exception Propagation

csharp

Copy code

using System;

class Program

static void Function1()

throw new Exception("Error in Function1");

static void Function2()

try
{

Function1();

catch (Exception ex)

[Link]("Caught in Function2: " + [Link]);

static void Main()

Function2();

Expected Output:

javascript

Copy code

Caught in Function2: Error in Function1

29. Custom Exception

csharp

Copy code

using System;

class MyCustomException : Exception

public MyCustomException(string message) : base(message)

{
}

class Program

static void Main()

try

throw new MyCustomException("This is a custom exception");

catch (MyCustomException ex)

[Link]([Link]);

Expected Output:

vbnet

Copy code

This is a custom exception

30. Checked vs Unchecked

csharp

Copy code

using System;

class Program
{

static void Main()

unchecked

int max = [Link];

int result = max + 1;

[Link](result);

Expected Output:

diff

Copy code

-2147483648

Advanced Topics

31. Lambda Expressions

csharp

Copy code

using System;

class Program

static void Main()

Func<int, int> square = x => x * x;

[Link](square(5));
}

Expected Output:

Copy code

25

32. Anonymous Types

csharp

Copy code

using System;

class Program

static void Main()

var person = new { Name = "Alice", Age = 30 };

[Link]([Link] + " is " + [Link] + " years old");

Expected Output:

csharp

Copy code

Alice is 30 years old

33. Extension Methods

csharp

Copy code

using System;
static class StringExtensions

public static string ToUppercase(this string str)

return [Link]();

class Program

static void Main()

string greeting = "hello";

[Link]([Link]());

Expected Output:

Copy code

HELLO

34. Delegates

csharp

Copy code

using System;

delegate void DisplayMessage(string message);

class Program
{

static void Show(string message)

[Link](message);

static void Main()

DisplayMessage del = Show;

del("Hello, Delegate!");

Expected Output:

vbnet

Copy code

Hello, Delegate!

35. Events

csharp

Copy code

using System;

class Publisher

public event Action Notify;

public void RaiseEvent()

{
Notify?.Invoke();

class Program

static void Main()

Publisher pub = new Publisher();

[Link] += () => [Link]("Event triggered");

[Link]();

Expected Output:

vbnet

Copy code

Event triggered

Additional Questions

36. Null Coalescing Operator

csharp

Copy code

using System;

class Program

static void Main()

{
string name = null;

[Link](name ?? "Default Name");

Expected Output:

mathematica

Copy code

Default Name

37. Null Conditional Operator

csharp

Copy code

using System;

class Program

static void Main()

string name = null;

int? length = name?.Length;

[Link](length);

Expected Output:

csharp

Copy code

<null>

38. Using Statement


csharp

Copy code

using System;

using [Link];

class Program

static void Main()

using (StreamWriter writer = new StreamWriter("[Link]"))

[Link]("Hello, file!");

Expected Output: (No console output, but a file [Link] is created with
"Hello, file!")

39. Properties

csharp

Copy code

using System;

class Person

private string name;

public string Name


{

get { return name; }

set { name = value; }

class Program

static void Main()

Person p = new Person();

[Link] = "Alice";

[Link]([Link]);

Expected Output:

Copy code

Alice

40. Indexers

csharp

Copy code

using System;

class MyCollection

private string[] data = new string[3];


public string this[int index]

get { return data[index]; }

set { data[index] = value; }

class Program

static void Main()

MyCollection collection = new MyCollection();

collection[0] = "Hello";

[Link](collection[0]);

Expected Output:

Copy code

Hello

41. Tuples

csharp

Copy code

using System;

class Program

static void Main()


{

var tuple = (Name: "Alice", Age: 30);

[Link]([Link] + " is " + [Link] + " years old");

Expected Output:

csharp

Copy code

Alice is 30 years old

42. Anonymous Methods

csharp

Copy code

using System;

class Program

static void Main()

Action<string> greet = delegate (string name)

[Link]("Hello, " + name);

};

greet("Bob");

Expected Output:
Copy code

Hello, Bob

43. Yield Keyword

csharp

Copy code

using System;

using [Link];

class Program

static IEnumerable<int> GenerateNumbers()

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

yield return i;

static void Main()

foreach (int number in GenerateNumbers())

[Link](number + " ");

Expected Output:
Copy code

01234

44. Dynamic Type

csharp

Copy code

using System;

class Program

static void Main()

dynamic obj = "Hello";

[Link]([Link]);

Expected Output:

Copy code

45. Nullable Types

csharp

Copy code

using System;

class Program

static void Main()

{
int? num = null;

[Link]([Link]);

[Link]([Link]());

Expected Output:

graphql

Copy code

False

46. String Format

csharp

Copy code

using System;

class Program

static void Main()

string name = "Alice";

int age = 30;

[Link]([Link]("Name: {0}, Age: {1}", name, age));

Expected Output:

yaml

Copy code
Name: Alice, Age: 30

47. DateTime Formatting

csharp

Copy code

using System;

class Program

static void Main()

DateTime now = [Link];

[Link]([Link]("yyyy-MM-dd"));

Expected Output:

bash

Copy code

(current date in yyyy-MM-dd format)

48. Enum Usage

csharp

Copy code

using System;

enum Days

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

}
class Program

static void Main()

Days today = [Link];

[Link](today);

Expected Output:

mathematica

Copy code

Wednesday

49. ReadOnly Fields

csharp

Copy code

using System;

class MyClass

public readonly int Value;

public MyClass(int value)

Value = value;

}
class Program

static void Main()

MyClass obj = new MyClass(42);

[Link]([Link]);

Expected Output:

Copy code

42

50. Static Constructors

csharp

Copy code

using System;

class MyClass

static MyClass()

[Link]("Static constructor");

public MyClass()

[Link]("Instance constructor");
}

class Program

static void Main()

MyClass obj1 = new MyClass();

MyClass obj2 = new MyClass();

Expected Output:

kotlin

Copy code

Static constructor

Instance constructor

Instance constructor

Common questions

Powered by AI

Encapsulation in C# is demonstrated through the use of properties, which provide a controlled way to access and modify data within a class. Properties enable the class designer to specify 'get' and 'set' accessors, encapsulating the class's data and allowing the implementation to be hidden from the client code. This contributes to improved software design by enforcing data integrity and providing the flexibility to change the internal implementation without affecting other parts of the code. For instance, in the sample code, the property 'Name' allows access to the private field 'name', ensuring that all modifications go through the property's set accessor, thereby maintaining control over the value assignment .

Exception handling in C# provides a structured way to detect and manage errors, improving program reliability and maintainability. The use of try-catch blocks helps by allowing developers to execute code that might throw exceptions within the 'try' block. If an exception occurs, control is transferred to the 'catch' block, where the error can be handled gracefully. This mechanism prevents runtime errors from crashing the program and provides a way to execute cleanup code, as shown in the example where accessing an array index out of range is caught and a message "Index out of range" is printed instead of crashing .

Method overloading in C# allows multiple methods in the same scope with the same name but differing in the type or number of parameters. This enhances functionality by providing flexibility to perform similar operations using different types and enabling more intuitive method names that improve readability. Overloading makes it easier for developers to design methods that work in different contexts with specific input data types. In the provided example, 'MyClass' has two 'Print' methods, one accepting an 'int' and another a 'string', allowing the same method name 'Print' to process and display different data types effectively .

Constructors in C# are special methods called when an object of a class is instantiated, playing a crucial role in initializing the object and preparing it for use. They set the initial state of an object by assigning default values or parameters passed during object creation. In terms of resource management, constructors can allocate resources or acquire necessary dependencies, ensuring the object is ready-to-use post-construction. This mechanism is essential for enforcing invariants in the class's logic from the moment of creation, as shown in the example where the class 'Person' uses a constructor to set the 'Name' property immediately when an object is instantiated with the given name .

Static methods belong to the class itself rather than to any specific object instance and can be called without creating an instance of the class. They are useful for operations that are independent of object state. In contrast, instance methods operate on specific instances and can access instance data through the 'this' reference, allowing for operations that depend on the object's current state. For example, if a static method is declared in a class, it can be accessed using the class name without instantiating the class, as seen in the example where `MyClass.StaticMethod()` is called directly. Trying to call an instance method using a class name without an object instance will lead to a compilation error .

Polymorphism in C# allows objects to be treated as instances of their parent class, enabling a single interface to represent different underlying forms (data types). Method overriding, a key aspect of polymorphism, allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This is crucial for designing flexible and scalable systems, as it allows code to be written in a more generalized form, delegating specific functionality to subclasses. In the example provided, a 'Dog' class overrides the 'Speak' method of its parent 'Animal' class to provide a specific implementation ('Woof'), showcasing polymorphism by utilizing the base class reference 'Animal a' to call overridden methods dynamically at runtime .

Recursive methods in programming are essential for solving problems that can be divided into smaller sub-problems of the same type, such as calculating factorials or traversing data structures like trees. They provide a clear and concise solution to complex problems that may otherwise require iterative approaches. However, one potential drawback in C# is the risk of stack overflow errors, which occur when the recursion is too deep, causing the call stack to exceed its limits. This can happen with poorly managed recursive calls or when base conditions are not defined correctly. Despite that, when used correctly, recursion can simplify code and algorithms, illustrated by a recursive factorial calculation as shown where `Factorial(n)` calls itself with `n-1` until reaching the base condition .

Interfaces and abstract classes are both used to define contracts and shared functionality but serve different purposes in C#. An interface provides a contract that implementing classes must adhere to, promoting loose coupling by only defining signatures without any implementation. In contrast, abstract classes can provide both method definitions and implementations, serving as a partially implemented template for subclasses. Use interfaces to enable multiple inheritance of type frameworks and achieve polymorphism without forcing a relationship between the types. Abstract classes are ideal for shared functionality. In robust system design, interfaces allow for greater flexibility and adaptability, while abstract classes facilitate code reuse and maintain common behavior among related classes. This dual capability results in scalable, maintainable, and flexible systems .

Finally blocks in C# complement try-catch constructions by providing a section of code that is guaranteed to execute regardless of whether an exception is thrown or caught. They are particularly useful for defining cleanup code, such as releasing system resources or closing file streams, ensuring that these actions are taken even if an error occurs. This helps maintain proper resource management and prevents resource leaks. In C#, a finally block follows both the try block and any of its catch blocks, and its code executes after try or catch, ensuring that essential cleanup operations run regardless of exceptions. Use finally blocks to guarantee execution of necessary code post-try or catch context .

Lambda expressions in C# are a concise way to represent anonymous methods using syntax that is both easy to read and write. They are often used in association with delegates to create inline function definitions that can be passed as arguments or assigned to variables. This enables developers to create compact and flexible code. Lambdas enhance delegate functionality by providing a quick method of implementing interface methods, reducing the need for additional named methods. In the example with a lambda expression `x => x * x`, this expression represents a function that returns the square of its input, succinctly enabling functional programming paradigms within C# .

You might also like