Coding Questions and Answers
1.
Write a method in c# which takes 2 input, 1st is a int array which is sorted and 2nd one is a int and the output expected is a subarray, when you add the elements in the subarray it should be equal to 2nd input parameter
static int[] GetOutput(int[] arrayItem, int sumItem)
{
List<int> resultSet = new List<int>();
for (int index = 0; index < arrayItem.Length -1; index++)
{
int sum = 0;
for (int j = index; j < arrayItem.Length - 1; j++)
{
if (sum <= sumItem)
{
sum = sum + arrayItem[j];
resultSet.Add(arrayItem[j]);
if (sum == sumItem)
{
return resultSet.ToArray();
}
}
else
{
resultSet.Clear();
break;
}
}
}
return new int[] { };
}
2. write a method that prints numbers from 1 to 10 using two threads. One thread should print odd numbers, and the other should print even numbers in the correct sequence.
3. <PurchaseDetail IsInvoiced="true" NumberOfItems="5" CustomerName="Abc">
<ItemName>Some Item</ItemName>
</PurchaseDetail> Write this in Serializable Object . If attributes are more, dynamic, how to retrieve the object.
Main
method, you are starting the asynchronous methods but not awaiting them. This means that the tasks may not complete before the program exits, which can lead to unexpected behavior or unhandled exceptions.Here’s how you can revise the code to follow best practices:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var a = MethodAPI();
var b = MethodDB();
var c = MethodFileSystem();
// Await all tasks to ensure they complete
await Task.WhenAll(a, b, c);
// Optionally, you can retrieve the results
var resultA = await a;
var resultB = await b;
var resultC = await c;
// Process results as needed
Console.WriteLine(resultA);
Console.WriteLine(resultB);
Console.WriteLine(resultC);
}
static async Task<object> MethodAPI()
{
// Simulate an asynchronous operation
await Task.Delay(1000);
return "API Result";
}
static async Task<object> MethodDB()
{
// Simulate an asynchronous operation
await Task.Delay(1000);
return "DB Result";
}
static async Task<object> MethodFileSystem()
{
// Simulate an asynchronous operation
await Task.Delay(1000);
return "File System Result";
}
}
4. Write sample code for Runtime polymorphism.
namespace2 { interface I1 { void SomeMethod(int a, int b); } } using namespace2; namespace1 { class1 : I1 { } } using namespace2; namespace6 { class2 : I1 { } } using namespace2; namespace8 { class3 : I1 { } } using namespace2; namespace15 { class4 : I1 { private int d = 0; public void SomeMethod(int a, int b) { try { var c = a/b; var e = c/d; Console.WriteLine(c); } catch (Exception ex) { Console.WriteLine("unknown error"); } catch(DivideByZeroException) { Console.WriteLine("cant divide by 0"); } } } } using namespace2; namespace3 { class MainClass { private void MainClass() { //get instance of the Class4, //should not use new initializer. //should not use namespace15 //not by injecting dependency from outside of this class } } }
Ans
No comments:
Post a Comment